If I pass an array into a function and make changes to the array within the function, the array that exists outside the function reflects those effects. E.g.:
var myArr = [1, 2, 3];
function popAll(arr) {
while(arr.length) {
arr.pop();
}
}
popAll(myArr);
console.log(myArr.length); // prints "0"
However, if I try to reassign the array reference to point to another array in the function, it does not stick:
var myArr = [1, 2, 3];
function reassign(arr) {
while(arr.length) {
arr.pop();
}
var newArr = [1,2,3,4,5];
arr = newArr;
}
reassign(myArr);
console.log(myArr.length); // still prints "0"!!
What am I missing? I want reassign(...) to assign the reference to the new array.
Edit:
I do not want to return the new array. I want to reassign the incoming reference. Also, I want to learn why JS has this behavior that appears to be inconsistent (or I don't know enough about to understand how it is consistent).
return newArr;and change line 9 tomyArr = reassign(myArr);