0

i want to know why we have to clone the objects instead of direct assigning.

 var obj1 = {x: 5, y:5};
 var obj2 = obj1;
 obj2.x = 6;
 console.log(obj1.x); // logs 6

i already got the solution but i want to know Why the obj2 working like a reference variable ?

fmsf
  • 36,317
  • 49
  • 147
  • 195
balaphp
  • 1,306
  • 5
  • 20
  • 40

1 Answers1

1

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?

Community
  • 1
  • 1
fmsf
  • 36,317
  • 49
  • 147
  • 195