It seems to be a very common thing but a bit confusing. I am stuck at 2 scenarios and trying to understand what is happening over here.
Scenario 1
let obj2 = {b:{c:{d:4}}}
let obj1 = {a:obj2['b']}
obj2['b'] =9
console.log(obj1)// --- > { a: { c: { d: 4 } } }
console.log(obj2)// --- > { b: 9 }
When I changed the value of obj2['b'] I was expecting obj1 will also change as obj1['a'] was
also referencing the same memory location but it didn't.
Scenario 2
let obj2 = {b:{c:{d:4}}}
let obj1 = {a:obj2['b']}
obj2['b']['c'] =9
console.log(obj1)// --- > { a: { c: 9 } }
console.log(obj2)// --- > { b: { c: 9 } }
When I changed the value of obj2['b']['c'] value of obj1['a']['c'] also changes because it was
referencing to the same memory location. That I understood, it is expected behavior.
I want an explanation of Scenario 1, why it didn't change the value of obj1 ?
a = {foo: 1}; b = a; a = {bar: 2}doesn't changebwhilea = {foo: 1}; b = a; a.foo = 2does? Because you've created the exact same scenario but made it more confusing using objects.obj2.breferences afterobj2.ais set to reference the previous value, the change to whatobj2.breferences is independent of the other object.