[JavaScript] Tracking Variable State

Haneul Choi·2021년 5월 26일
0

JavaScript

목록 보기
3/3
post-thumbnail
function double(arr) {
 for(let i = 0 ; i < arr.length ; i ++ ) {
 	arr[i] = arr[i] * 2;
 }
  return arr;
}
const array = [1,2]
const doubleArray = double(array);
console.log(array); // [2,4]
console.log(doubleArray); // [2,4]

Suppose that you have a variable that will be used in various functions in your program. Also suppose that you want to keep this variable as it is without a change over the period of time of execution. In the program above, the variable 'array' that is [1,2] will not be kept original after a specific line execution. Look into the underlined line, where a function 'double' is called and executed. Then you can go deeper inside that function to find out that the originally passed parameter is the 'array' variable which then by function mechanism is returned at the end. The problem with this is that the 'double' function essensially changes values of each element in the passed array. That is why when by the time it is returned, the 'array' variable is no longer [1,2], rather [2,4].

// The code fix to prevent changes in original variable state:
function  double(arr) {
    let localArray = [];
    for(let i = 0 ; i < arr.length ; i ++ ) {
    	localArray.push(arr[i]*2);
    }
    return localArray;
}
const array = [1,2]
const doubleArray = double(array);
console.log(array); // [1,2]
console.log(doubleArray); // [2,4]
profile
Web Developer 웹 개발 공부하는 사람

0개의 댓글