I was reading on this blog about how if an object or array were changed inside of a function, the value in memory that was pointed to would be changed as well, the same as if it were changed outside the function.
var a = [1,2,3],
b = a;
b[0] = 5;
console.log(a); // [5, 2, 3]
would result in the same as
var a = [1,2,3],
b = a;
var arrayFunction = function(arr){
arr[0] = 10;
};
var arr = arrayFunction(b);
console.log(a, b, arr) // [10, 2, 3], [10, 2, 3], [10, 2, 3];
Yet what I can't understand is why reassigning multiple array values within the function does not change the values outside of it:
var a = [1,2,3],
b = a;
var arrayFunction = function(arr){
arr = ["a", "b", "c"];
return arr;
};
var result = arrayFunction(b);
console.log(result) //["a", "b", "c"]
console.log(a, b); //[1, 2, 3], [1, 2, 3]
Why does this not change the pointed to value in memory like in the first example?
Probably a better job of writing out the examples on the JSBIN
Answer
Remember that, within the function, arr
is not the actual array; arr
is a reference that points to the array.
So when you say arr[0]
, you're retrieving the array, and then getting or updating an item in it.
But when you say arr = ["a","b","c"]
, you are creating a new object (on the right side) and then turning arr
into a reference that points to the new object.
No comments:
Post a Comment