let a = [1, 2, 3]
let b = a
a = [1, 2]
console.log(b)
I expected that the result will be 1, 2 but it is 1, 2, 3
let a = [1, 2, 3]
let b = a
a = [1, 2]
console.log(b)
I expected that the result will be 1, 2 but it is 1, 2, 3
Initialize a variable to refer to an array
let a = [1,2,3];
Copy that reference into a new variable
let b = a;
Modify the array using the original reference
a.splice(2, 1);
Display the changed array [1,2] using the new reference
console.log(b);
You’ve changed the pointer of the variable a
to a new array, but the old array still exists because b
is still pointing to it. All you’ve done is reassign the array that the variable a
is now pointing to.
This is working as expected. You’ll get the result you were trying to achieve by mutating the array a
is pointing to instead of completely reassigning it. Ie
let a = [1, 2, 3]
let b = a
a.pop()
console.log(b)