When arrays are assigned to another variable, the reference is passed as opposed to values. This is confirmed when you compare two arrays using ==
operator and it returns true
var a = [[1,2],[3,4],[5,6]];
var b = a; // b = [[1,2],[3,4],[5,6]]
var c = [].concat(a); // c = [[1,2],[3,4],[5,6]]
a == b; //true
a == c; //false
With the above inputs, when I modify the array b
, it mutates array a
, but not c
.
b.push([7,8]); // b = [[1,2],[3,4],[5,6], [7,8]]
a; //a = [[1,2],[3,4],[5,6], [7,8]]
c; //c = [[1,2],[3,4],[5,6]]
But when I do the below, it mutates c
.
b[0].push(5); // b = [[1,2,5],[3,4],[5,6], [7,8]]
a; //a = [[1,2,5],[3,4],[5,6], [7,8]]
c; //c = [[1,2,5],[3,4],[5,6]]
Why does this happen? This behavior happens with the usage of array methods that mutates the array.
.concat()
does a shallow copy. So after the line:
var c = [].concat(a);
c
and a
reference different arrays, but c[0]
and b[0]
and a[0]
all reference the same array.
Quoting from MDN:
concat copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With