Reputation: 47
I have a simple question
let obj1 = {};
obj2= obj1;`
Here obj1 and obj2 are referencing the same object in the memory i.e. obj1===obj2 --> true
. So by this logic any operation on obj2 will affect obj1.
Now if I assign a property to obj2
let obj1 = {};
obj2 = obj1;
obj2['a'] = {};
obj2 = obj2['a']; // why this operation didn't change obj1, if they are referencing the same object ?
console.log(obj1); // -- > { a: {} };
console.log(obj2); // -- > {};
now obj1===obj2 --> false
why is this ?
Also How come obj2 = {} is different then obj2 = obj2['a']
?
A screenshot for clarifying myself
Thanks for your help in advance.
Upvotes: 1
Views: 476
Reputation: 147403
For objects, the assignment operator =
assigns a reference to the object.
So in:
let obj1 = {};
let obj2 = obj1;
both obj1 and obj2 reference the same object. Now:
obj2['a'] = {};
creates a new property a and assigns it a value that is a reference to a new object. Since both obj1 and obj2 reference the same object, you'll also find:
obj2.a === obj1.a
But then:
obj2 = obj2['a']; // why this operation didn't change obj1, if they are referencing the same object ?
You've now assigned a different object to obj2, so it now references the new object initially assigned to obj2.a
and:
obj1.a === obj2;
So obj1 was modified (or more correctly, the object referenced by obj1 was modified).
Some code:
// obj1 and obj2 reference the same object
let obj1 = {};
let obj2 = obj1;
console.log('obj2 === obj1 ' + (obj2 === obj1)); // true
// Assign new object to obj2.a
obj2['a'] = {};
// Affects obj1
console.log('obj2.a === obj1.a ' + (obj2.a === obj1.a)); // true
// Assign new object to obj2
obj2 = obj2['a'];
// obj2 now references a different object to obj1
console.log('obj1 === obj2 ' + (obj1 === obj2)); // false
// obj1.a still references new object
console.log('obj1.a === obj2 ' + (obj1.a === obj2)); // true
Upvotes: 3
Reputation: 1
obj2 is an object, obj2[a] is another object. The result of comparing two objects is false.
{} === {} // false
Upvotes: 0