The spread operator vs. structuredClone()

The spread operator vs. structuredClone()

Erick

Written by Erick /

Let's say we have this object that we need to copy:

TS
const original = {
  title: 'Party',
  attendees: ['Erick']
}

Normally, we'd do something like this:

TS
const copy = {
  ...original
}

Cool. Let's invite Delphine.

TS
copy.push('Delphine')
copy.attendees
// [ 'Erick', 'Delphine' ]

It works as expected. It's worth knowing, however, that this also affects the original object:

TS
original.attendees
// [ 'Erick', 'Delphine' ]

Maybe that's only a problem if she wasn't invited? 🤷🏻‍♂️

Anyway, let's find out why modifying the copy affects the original.

TS
const originalArray = [1, [2, 3]]
const shallowCopy = [...originalArray]

console.log(shallowCopy === originalArray) // false
console.log(shallowCopy[1] === originalArray[1]) // true

Though a new array is created with a reference different to the original, the reference to the nested array is not copied, it simply points to the original. The same goes for our earlier example where modifying the attendees in the copy also modifies the original.

Though this might not be a problem for your use case, it's definitely worth knowing about a built-in method in JavaScript if you'd like to keep things a bit more immutable.

structuredClone()

Let's try this again using structuredClone without touching cantTouchThis.

TS
const cantTouchThis = {
  singer: 'MC Hammer',
  placesSingerHasBeen: ['around the world', 'London']
}

const deepCloneOfCantTouchThis = structuredClone(cantTouchThis)

// Adding another element to placesSingerHasBeen
deepCloneOfCantTouchThis.push('The Bay')

deepCloneOfCantTouchThis.placesSingerHasBeen
// ['around the world', 'London', 'Bay']

cantTouchThis.placesSingerHasBeen
// ['around the world', 'London'];

The more you know 💫

Links

MDN Docs on structuredClone()

Credits

Image by rawpixel.com