to my understanding, both array and objects are Pass By Reference based on the memory address, so if I create another variable and point to the array/object, and mutate any of the values, another value should also be changed.
However, I don't quite understand how it works here. I am pointing to array1 and modifying array1 to empty, why the value at anotherArray does not change?
var array1 = [1,2,3,4,5,6,7]; // Created array
var anotherArray = array1; // Referenced array1 by another variable
array1 = []; // Empty the array
console.log(anotherArray); // Output [1,2,3,4,5,6,7]
I can understand the below example why the anotherArray becomes [] empty because it is passed by reference, but why the anotherArray still output [1,2,3,4,5,6,7] for the above?
var array1 = [1,2,3,4,5,6,7]; // Created array
var anotherArray = array1; // Referenced array1 by another variable
array1.length = 0; // Empty the array by setting length to 0
console.log(anotherArray); // Output []
Thank you.
array1refers to, you are reassigning whatarray1refers to. In the second sample you are modifying the array thatarray1refers toarray1 = [], you're simply replacing the value.