Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am I missing with the understanding of Arrays?

Tags:

javascript

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.

like image 268
Harish Avatar asked May 30 '15 08:05

Harish


1 Answers

.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.

like image 113
nnnnnn Avatar answered Oct 17 '22 00:10

nnnnnn