Let's look at what this code does step by step:
1 -
var obj1 = {x: 5, y:5};
Create an object {x: 5, y:5}
and store its reference in variable obj1
2 -
var obj2 = obj1;
Create variable obj2
and attribute the value of obj1
to it. As the value of obj1
is a reference to an object, then obj2
will now be pointing to the same object.
3 -
obj2.x = 6;
Change the value of the property x
in the object being referenced
4 -
console.log(obj1.x); // logs 6
Print x
property from the object being referenced by obj1
. As obj1
and obj2
are pointing at the same place, the output is 6
.
This is the same behavior that any language that works with references to objects will have. Java, C, C++, C#, etc. In OOP languages you normally have a clone()
method that will do a field by field copy. But in the case of JS, such method doesn't exist, you need to do a deep copy of every element. You can find a nice set of answers regarding how to clone elements in JS here: What is the most efficient way to deep clone an object in JavaScript?