If:
var x = [1, 2, 3];
var y = [4, 5, 6]
;
var z = x;
and then if z[2] = y[0]
;
Why is it that console.log(x);
is [1, 2, 4]
and not [1, 2, 3]
?
If:
var x = [1, 2, 3];
var y = [4, 5, 6]
;
var z = x;
and then if z[2] = y[0]
;
Why is it that console.log(x);
is [1, 2, 4]
and not [1, 2, 3]
?
When you do var z = x;
you are no creating a new array, entirely separate from x, you are simply creating a reference to the original array. Hence, the change happens in both.
If you want to create a new object, you can use the new ES6 spread operator
var z = {...x};
Have a look at this answer for a more in-depth explanation of passing by reference and by value.
Cuz the 'z' variable is a pointer to the same array that 'x' point to.
An array in JavaScript is also an object
and variables only hold a reference
to an object, not the object itself. Thus both variables have a reference to the same object. So changing made through one variable reflected in other as well.
var x = [1, 2, 3];
var y = [4, 5, 6];
var z = x;
z[2]=y[0];
console.log(x);
var w=Object.assign([],x);
w[0]=y[1];
console.log(x);
console.log(w);
Look at the example. If you want to change in a new variable and don't want reflected that change in original one than use Object.assign
.