0

Look at the following code:

var x = [1, 2, 3], y;
y = x;
y.splice(0,0,4);

which gives:

y = [4, 1, 2, 3]    //  (correct)

x = [4, 1, 2, 3]    //  (why did this change too?)

Why did the x array change when I called .splice() on y?

pomeKRANK
  • 47
  • 7

1 Answers1

4

Objects (including arrays) are passed by reference (effectively, this is what it does... -- purists may disagree with this statement). The splice method mutates the original array. Therefore, since x and y point at the same array, a splice on y will change x as well. To do a shallow clone of x in to y, do y = x.slice(). (Note that any objects within x won't be cloned; they'll be passed by reference.)

var a = [1,2,3];
var b = a;
a[0] = 42;
alert(b[0]); // will show 42
var c = a.slice(); // explicitly makes a copy
a[1] = 6502;
alert(c[1]); // will show 2, not 6502

Taken from value type reference type object in javascript

Community
  • 1
  • 1
Dawson Toth
  • 5,580
  • 2
  • 22
  • 37