I wanted to understand why when I make a copy of an object and reassign the "nestedObject" property from the obj2 (copy) is only modified in the obj2 (copy) and not in the original object. But when the property foo2 is reassign the new value is assigned to both objects.
let obj1 = {
foo1: 1,
nestedObj: {
foo2: 2
}
}
let obj2 = obj1
console.log(obj1);
console.log(obj2);
// { foo1: 1, nestedObj: { foo2: 2 } }
// { foo1: 1, nestedObj: { foo2: 2 } }
obj2 = obj2.nestedObj;
console.log(obj1);
console.log(obj2);
// { foo1: 1, nestedObj: { foo2: 2 } }
// { foo2: 2 }
obj2.foo2 = 3
console.log(obj1);
console.log(obj2);
// { foo1: 1, nestedObj: { foo2: 3 } }
// { foo2: 3 }
I assume that the difference is when copy by value or by reference. But I have not been able to figure it out on my own. Thank you very much for your response and time.
I wanted to understand why when I make a copy of an object and reassign the "nestedObject" property from the obj2 (copy) is only modified in the obj2 (copy) and not in the original object. But when the property foo2 is reassign the new value is assigned to both objects.