Search code examples
javascriptecmascript-6babeljsmutationspread-syntax

Why the obj is being mutated when I am modifying the cloned obj ( using {...})?


Lets take an object d.

var d =  { 
  "e":{
    "f": 3
  }
}

Now copying d to t with {...} and assigning new prop.

var t = {...d}
t.e._f = 4

Why the object d is being mutated to

{
  "e": Object {
    "_f": 4,
    "f": 3
  }
}

Solution

  • You are doing shallow copy. {...d} is equivalent to Object.assign({}, d) which in turn copies properties one level deep. Docs.

    For deep cloning, we need to use other alternatives because Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value.

    So t.e === d.e referencing the same object.