Question

this.lastLocations[0] = this.locations[0];
this.locations[0].x++;

When this code is executed it increments both locations[0].x and lastLocations[0].x. I want it to just change locations[0].x. Is this because javascript is assigning the reference rather than the value? Or is the problem somewhere else in my code?

Was it helpful?

Solution

Objects in javascript are assigned by reference so both your variables are pointing at the exact same object.

So, when you do this:

this.lastLocations[0] = this.locations[0];

Then, both this.lastLocations[0] and this.locations[0] now point to the exact same object. If you make a change to that object via either one of these variables, then that change will show via the other variable (because they both point at the exact same object).

If you want to assign a copy, then you literally have to make a copy of the object (by creating a new object and then copying over all the properties from the original to the new object) and assign that new copy.

There are numerous other posts on methods for cloning/copying an object:

What is the most efficient way to deep clone an object in JavaScript?

How do I correctly clone a JavaScript object?

is it possible in Javascript to tell an object to stop having reference behavior with another object

And, some other related questions:

Do objects pushed into an array in javascript deep or shallow copy?

Javascript by reference vs. by value

OTHER TIPS

Everything in JavaScript is passed and assigned by value.

"Objects" are not values in JavaScript. The only values in JavaScript are primitives and references (pointers to objects). So array1[0] is either a primitive or pointer to an object, and array2[0] is either a primitive or pointer to an object.

When you do array1[0] = array2[0], it assigns the object pointer so that both pointers point to the same object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top