Canvas
Canvas

Reputation: 5897

Duplicated variables in an array when not meant to be duplicated

I have this very small piece of code

for(var i = 0; i < 4; i ++)
{
    var ball = balls[i];
    totalBalls.push( ball );
}

When i try this

console.log( totalBalls[0].xPos ) // = 10
console.log( totalBalls[1].xPos ) // = 10
balls.xPos += 10;
console.log( totalBalls[0].xPos ) // 20
console.log( totalBalls[1].xPos ) // 20

Why is the second element in the array the same as the first element in the array?

Upvotes: 0

Views: 49

Answers (1)

Paul S.
Paul S.

Reputation: 66304

Why is the second element in the array the same as the first element in the array?

Objects are kept as references, i.e.

a = {foo: 'bar'};
a.foo; // "bar"
b = a;
b.foo = null;
a.foo; // null

So when you do push, it doesn't create a new Object which is a clone of ball, but rather creates a new reference to the place in memory where ball already is.

Upvotes: 2

Related Questions