0

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.

Marcelo Alarcon
  • 394
  • 1
  • 3
  • 17
  • Assigning an object to a variable/property always creates a reference. Copying objects is potentially quite complicated, and can be a difficult challenge. See the [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) API. – jsejcksn Jan 13 '23 at 22:00
  • The best thing to do would probably be to visualise this at http://pythontutor.com. – deceze Jan 13 '23 at 22:00
  • [^](https://stackoverflow.com/questions/75114793/javascript-object-copy#comment132554205_75114793) @deceze That visual debugger is a great teaching tool! Thanks! – jsejcksn Jan 13 '23 at 22:02
  • See also: [Is JavaScript a pass-by-reference or pass-by-value language](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Tibrogargan Jan 13 '23 at 22:02

0 Answers0