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'
Lessons in this unit:
Are you intimidated by Git? Can’t figure out
merge vs rebase? Are you afraid of screwing up
something any time you have to do something in
Git? Do you rely on ChatGPT or random people’s
answer on StackOverflow to fix your problems?
Your coworkers are tired of explaining Git to
you all the time? Git is something we all need
to use, but few of us really master it. I
created this course to improve your Git (and
GitHub) knowledge at a radical level. Launching
May 21, 2024. Join the waiting list!