Reputation: 21
I'm trying to understand the exact behavior of arrays in Javascript. I know that they work by reference. But I was confused when I came across this piece of code:
let arr1 = [1,2,3];
let arr2 = arr1;
arr1[2] = 4;
console.log(arr2); // [1,2,4]
arr1 = [2, 3, 4];
console.log(arr2); // [1,2,4] why not [2, 3, 4]
So how exactly do arrays behave in javascript?
Upvotes: 1
Views: 62
Reputation: 6501
Think of it like this, a variable is a pointer for an object in memory, now:
arr1
) to object [1,2,3]
[1,2,3]
, this is what is meant by reference.[1,2,3]
's last value to 4
. At this point arr1
and arr2
still points to this object.arr1
a NEW object with content [2,3,4]
. At this point arr2
points still to the old [1,2,4]
object.Upvotes: 2
Reputation: 171698
When you do let arr2 = arr1;
both variables share reference to same actual array.
However if you reassign one of those variables to a different array they no longer share same reference and are completely isolated from each other
Upvotes: 2