-1

Probably this is a dumb question :)

var x = [1, 2, 3];
var y = x;   // Value of x is stored in y
y[0] = 5; 
alert(x[0]); // returns 5. Why?

x[0] ideally should be 1, but why is it 5?

TheGuy
  • 349
  • 6
  • 17
  • 4
    Both the variables `x` and `y` hold references to the same array (that's what object values are). There is only one array, and that's the one whose `0` index you are modifying. – Bergi May 18 '16 at 17:58
  • You copied *the reference* not *the value* of the array. What you what to do is actually *clone* the array. – Matt Burland May 18 '16 at 17:59

1 Answers1

1

x contains address of first element of array and x = y passes that to y. So y[0] is same as x[0]. This is because x[0] yields address as x+0 and y[0] as y+0. Since y and x are same so y[0] and x[0] point to same location.

Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20