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?

3
  • What language is this? Commented Apr 10, 2016 at 1:48
  • Answered pretty well by stackoverflow.com/questions/7480654/… Commented Apr 10, 2016 at 2:07
  • ok, so how do you keep x the same ? Commented Apr 10, 2016 at 2:09

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.