Objects: Cloning objects

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:

0: Introduction
1: How to create an object
2: Object properties
3: Objects are passed by reference
4: Methods
5: Passing objects as function arguments or returning objects from a function
6: Accessing a property of the object inside a method using `this`
7: Object destructuring
8: ▶︎ Cloning objects
9: Sort an array of objects by a property value
10: Merging two objects into one
11: apply, call, bind