Search code examples
javascriptjavascript-objectsdestructuring

Will object destructuring paired with a spread operator create a new reference in memory?


I have a function where I want to omit a property ('uuid') from an object ('readingListObj') without mutating the object itself.

Will implementing object destructuring paired with the spread operator on the 'readingListItem' object create a new reference for 'uuid' and 'item'?

removeId(readingListObj) {
    const { uuid, ...item } = readingListObj // <---will this line create a new ref for'uuid' and 'item'?

    return item
  }

Solution

  • The simplest approach would be to just check

    const object1 = {a: 1, b: 2, c: {c: 1}};
    const {a, ...object2} = object1;
    
    // try to modify basic value property 
    object2.b = 3;
    console.log(object2.b, object1.b); // returns different values meaning that objects are indeed different
    
    // try to modify object value property
    object2.c.c = 2
    console.log(object2.c.c, object1.c.c) // returns the same values

    The second modification returning same values means that even though destructurizing created a new object it didn't do a deep copy of it, so there is still a possibility of mutation of the original object.