Cloning and Deep Copying in JavaScript

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

Cloning and Deep Copying in JavaScript

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Assigning Objects Copies References

As we know JavaScript object assignments work by using references. This means that cloning of objects cannot be done by simple assignment.

const john = { name: 'John' };

const copy = john;

copy.name = 'Jane';

console.log(john.name); // Jane 😱

Create Shallow Copy using Spread Operator

A simple way to create a shallow copy is by using the spread operator.

const john = { name: 'John' };

const copy = { ...john };

copy.name = 'Jane';

console.log(copy.name); // Jane ✅

console.log(john.name); // John ✅

But this does not create a deep copy.

const john = {
name: { firstName: 'John', lastName: 'Doe' },
};

const copy = { ...john };

copy.name.firstName = 'Jane';

console.log(john.name.firstName); // Jane 😱

Deep Copy using JSON Serialization

One way that developers have traditionally used to create a deep copy, is by serializing the object into a json string and then deserializing that string into a new object.

const john = {
name: { firstName: 'John', lastName: 'Doe' },
};

const copy = JSON.parse(JSON.stringify(john));

copy.name.firstName = 'Jane';

console.log(copy.name.firstName); // Jane ✅

console.log(john.name.firstName); // John ✅

But using JSON serialization means we cannot clone things whose types are not preserved in JSON format e.g. dates, maps and sets

const john = {
name: { firstName: 'John', lastName: 'Doe' },
dob: new Date(1984, 0, 1),
};

console.log(john.dob, john.dob instanceof Date); // Date (1984 Jan 1)

const copy = JSON.parse(JSON.stringify(john));

console.log(copy.dob, typeof copy.dob); // string (1984 Jan 1) 😱

Cloning with structuredClone

const john = {
name: { firstName: 'John', lastName: 'Doe' },
dob: new Date(1984, 0, 1),
};

const copy = structuredClone(john);

copy.name.firstName = 'Jane';

// ✅ copy property modified
console.log(copy.name.firstName); // Jane

// ✅ original property left intact
console.log(john.name.firstName); // John

// ✅ copy type preserved
console.log(copy.dob, copy.dob instanceof Date); // Date (1984 Jan 1)

Limitations

One thing to note is that structuredClone only works for properties and you can think of it as a clone function for the structure of the original object. It doesn’t clone custom functions present on the object. This is because methods in JavaScript can reference external variables. So if want to clone objects with custom functions, it is best to create them manually.

javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

As we know, JavaScript object assignments work by using references. This means that cloning of objects cannot be done by using simple assignment. Let's demonstrate that by creating a simple object containing the name property pointing to the string. John, if you try to create a copy by simply assigning it to a different variable, it'll actually be a reference to the same object. So if you modify any properties on the copy, we are essentially modifying the original object, and we can verify this by executing this simple piece of code. A simple way to create a shallow copy is by using a feature

00:34

that we've already looked at, which is the spread operator. So we create a new object for the copy by spreading in the existing John object. And now if you modify this copy, of course the copy property will be changed, but the original John object will be left intact. Note that the spread operator does not create a deep copy. So if our original object contains nested objects, for example, name here is an object by itself. Even if you create a copy of John using the spread operator, the nested object is not going to be cloned and will continue to refer to the original john.name.

01:09

So if you modify the properties of copy.name, john.name being the same object is what is going to get modified. One trick that developers have traditionally used to create a deep copy is by serializing that object into adjacent string and then des serializing that string into a new object. So our object contains nested objects, for example, john.name as an object by itself. And this time we create the copy by first using json dot string I to serialize the object to a string, and then parsing that string using json dot parse to create a new object. Now, when we modify the nested object within the copy,

01:45

only the copy is going to get modified, but the original John object is going to remain intact, and we can verify that by executing this code. But using json serialization means that we cannot clone things whose types are not preserved in JSON format. For example, dates, maps, and sets. So we start off with an object that has a date of birth property, which is of type date, and we create a copy by using json dot stringier, followed by Jason Pass. Because the day type is not preserved over J serialization, we essentially end up with the date

02:17

of birth property being a string. Fortunately, j serialization for cloning is not a trick that you need to remember anymore because modern JavaScript has a built-in method called structured clone. We pass in the object that we want to copy into structured clone, and it creates a new cloned copy. If you modified even nested properties of the copy, only the object in the copy is going to get modified. The original object will remain intact. Additionally, within the copy, the types are preserved as well. For example, maps and sets will copy around just fine.

02:51

And similarly, date is going to continue to be a date. One thing to note is that structured clone only works for properties, and you can think of it As a clone for the structure of the original object. It doesn't clone custom functions that might be present on the object. This is because methods in JavaScript can reference external variables. So if you want to clone objects with custom functions, it is best to create them manually.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36