When you have an object, how do you perform a copy of it?
You already know that primitive types are passed by value and so a simple copy with the assignment operator works:
const a = 1
const b = a
But with objects, that are passed by reference, we can’t do it so simply.
This would just make b
point to the same object that a
points to:
const a = {}
const b = a
We have some solutions.
The simplest is to use the spread operator:
const a = { test: 'test' }
const b = { ...a }
Now b
is a new object with the same properties as a
, but completely independent.
Both we have one problem. If some properties of the object are in turn objects, then.. only their references are copied:
const a = { dog: { name: 'test' } }
const b = { ...a }
a.dog.name= 'good dog'
b.dog.name //'good dog'
In this case, you need to perform deep cloning, and JavaScript does provide a way to do so out of the box using the structuredClone()
function:
const a = { dog: { name: 'test' } }
const b = structuredClone(a)
a.dog.name= 'good dog'
b.dog.name //'test'