1
var a = [], b = [];
a.push('a');
a.push('b');
a.push('c');
b = a;
b.push('d');
console.log(a);

Why is a = ["a", "b", "c", "d"] ?, how to avoid this cross reference when doing b=a; I would like just to have 2 separates objects, independants

and at the end a = ["a", "b", "c"], and b = ["a", "b", "c", "d"]

1

5 Answers 5

1

When you assign a to b, you are actually assigning a reference to a. So any change made to b will also affect a. To do what you really wanted, try:

b = [].concat(a);

which will make an actual copy of a.

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

Comments

1

In JS arrays are also objects (instance of Array object) and as such objects in JS are assigned by reference not by value, so when you do:

b = a

b is now assigned by reference to a, hence it will affect the a array.

To do what you want to do, you can do:

b = a.slice();

Here is an example:

var a = [], b = [];
a.push('a');
a.push('b');
a.push('c');
b = a.slice();
b.push('d');
console.log(a);

Result:

[a, b, c]

Comments

0

Because variables reference objects, they do not copy them.

You can use

var a = [], b = [];
a.push('a');
a.push('b');
a.push('c');
b = a.slice();
b.push('d');
console.log(a);

Comments

0

Because assignment does not copy variable content. (See the related Is this a variable scoping bug in NodeJS or do I just need more sleep question.)

For arrays, you could use concat to create a (shallowly) copied array:

a = [1,2,3]
b = [].concat(a)
b.push(4)

... or sliceas the other answers say.

Comments

0

Once you do b = a both a and b point to the same array in memory; you need to push the elements to both a and b separately, or once you push elements to a you can loop through it and push the same to b, e.g.

for ( var i = 0; i < a.length; i++ ){ b.push( a[i] ); }

Comments

Your Answer

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