If I mutate the value of myArray
within myFunction
, the new myArray
is updated:
let myArray = [1, 2, 3];
console.log( JSON.stringify(myArray) ); // [1, 2, 3]
function myFunction(arr) {
arr.push(4);
console.log( JSON.stringify(arr) ); // [1, 2, 3, 4]
return arr;
}
myFunction(myArray);
console.log( JSON.stringify(myArray) ); // [1, 2, 3, 4]
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
However, if I try to reassign myArray
with arr = [0];
within myFunction
, myArray
stays the same.
let myArray = [1, 2, 3];
console.log( JSON.stringify(myArray) );; // [1, 2, 3]
function myFunction(arr) {
arr = [0];
console.log( JSON.stringify(arr) ); // [0]
return arr;
}
myFunction(myArray);
console.log( JSON.stringify(myArray) ); // [1, 2, 3]
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
Why can't myArray
be reassigned in the example above, but can be if I do this:
let myArray = [1, 2, 3];
myArray = [0];
console.log(myArray); // [0]