2

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]?

Debbot
  • 49
  • 3

3 Answers3

2

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.

bugs
  • 14,631
  • 5
  • 48
  • 52
  • Thank you @bugs! Does this work differently for non-arrays? var a = 1; var b = 2; var c = a; c = 2; console.log(a); = 1 – Debbot Mar 30 '18 at 19:24
  • Primitive types, such as strings or numbers, are indeed passed by value, so the problem you had above would not happen in this case. – bugs Mar 30 '18 at 19:25
1

Cuz the 'z' variable is a pointer to the same array that 'x' point to.

Maor M
  • 11
  • 3
  • 1
    Please explain your answer so that everyone understands. Answers with explanations are helpful and appreciated by all. – Munim Munna Mar 30 '18 at 19:30
0

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.

yajiv
  • 2,901
  • 2
  • 15
  • 25