-1

Say you have an object obj = { a : [1, 2] } and you create a clone of it objClone = Object.assign({}, obj) and when you modify Object.values(objClone)[0][1], then the parent obj is also modified. Can someone explain why?

Maksymas
  • 9
  • 2
  • 3
    `Object.assign()` makes a **shallow copy** of the source object. – Pointy Apr 14 '20 at 05:05
  • But changing Object.values(objClone)[0] doesn't change the parent object. Can you explain why @Pointy – Maksymas Apr 14 '20 at 05:08
  • Because `Object.values()` also makes a shallow copy. – Pointy Apr 14 '20 at 05:11
  • `Object.values` returns a *new* array reference, but all the elements (shallowly copied) still refer to the original elements, thus if you mutate a value in the "copied" array it mutates the same value reference in the original array. – Drew Reese Apr 14 '20 at 05:11

1 Answers1

1

In:

let objA = { a : [1, 2] }

the value of objA.a is a reference to the array created by the array literal. So when you copy the object:

let objB = Object.assign({}, objA)

then the value of objB.a is a copy of the value of objA.a, so is a reference to the same array.

That is often referred to as a "shallow copy", that is, it's just a simple copy of the value without resolving references to copy whatever they reference.

When you do:

console.log(objA.a)

then the reference is resolved so it prints the contents of the array, not the actual value of the reference (which would be a bit useless).

RobG
  • 142,382
  • 31
  • 172
  • 209