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

3
  • Because you're referencing the same array. Commented Mar 30, 2018 at 19:20
  • Memory references! Commented Mar 30, 2018 at 19:20
  • stackoverflow.com/questions/518000/… Commented Mar 30, 2018 at 19:23

3 Answers 3

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.

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

2 Comments

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
Primitive types, such as strings or numbers, are indeed passed by value, so the problem you had above would not happen in this case.
1

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

1 Comment

Please explain your answer so that everyone understands. Answers with explanations are helpful and appreciated by all.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.