Advertisement
  1. Code
  2. Coding Fundamentals

The Best Way to Deep Copy an Object in JavaScript

Scroll to top
Read Time: 8 min

In this article, you'll learn what shallow and deep copying are, and the best way to deep copy an object in JavaScript.

Shallow Copying vs. Deep Copying

In a reassignment operation involving primitive data types such as strings, numbers, and booleans, the original variable is copied by JavaScript. 

For example, consider the following code:

1
let x = 3
2
y = x //  x is copied into y

3
4
y++ // y is incremented

5
6
console.log(y) // now 4

7
console.log(x) // still 3

In this case, the value 3 is copied into y, and then x is disconnected from y. So mutating y does not affect x.

Conversely, with non-primitive data types like arrays and objects, only a reference to the values is passed. So when the copy is mutated, the original also gets mutated. This is also known as shallow copying.

1
let adam = {name: "Adam"};
2
3
let jason = adam;
4
jason.name = "Jason";
5
6
console.log(adam.name);  // outputs "Jason"

7
console.log(jason.name); // outputs "Jason"

If we instead want to copy an object so that we can modify it without affecting the original object, we need to make a deep copy

5 Ways to Deep Copy Objects in JavaScript

In JavaScript, we can perform a copy on objects using the following methods:

Method Pros Cons
shallow copy with = clear and direct, the default only shallow copies objects
JSON.stringify() and JSON.parse() deep copies nested objects doesn't copy functions
Object.assign() copies the immediate members of an object—including functions doesn't deep copy nested objects
the ... spread operator simple syntax, the preferred way to copy an object doesn't deep copy nested objects
Lodash cloneDeep() clones nested objects including functions adds an external dependency to your project

These methods all have their pros and cons. Let's take a closer look at each of them.

Shallow Copy an Object by Assignment

You can create a shallow copy of an object by simply assigning the original object to a new variable. 

Consider the following object:

1
const user = {
2
    name: "Kingsley",
3
    age: 28,
4
    job: "Web Developer"
5
}

To create a copy of the object user, we assign the object to a new variable like so:

1
const clone = user
2
3
console.log(user)
4
console.log(clone)
5
6
/* 

7
{

8
  age: 28,

9
  job: "Web Developer",

10
  name: "Kingsley"

11
}

12


13
{

14
  age: 28,

15
  job: "Web Developer",

16
  name: "Kingsley"

17
}

18
*/

As observed in the console output, we have now copied the object from user into clone.

However, all we did was create a reference to the original object. Whenever we mutate a property in the object clone, we'll also end up mutating the original object (user) as we do in the following code:

1
clone.age = 30
2
3
console.log(user)
4
console.log(clone)
5
6
/* 

7
{

8
  age: 30,

9
  job: "Web Developer",

10
  name: "Kingsley"

11
}

12
{

13
  age: 30,

14
  job: "Web Developer",

15
  name: "Kingsley"

16
}

17
*/

So when a non-primitive data type (array or object) is assigned to a new variable, JavaScript makes a shallow copy of the original object.

Copy an Object With JSON.stringify() and JSON.parse()

The JSON.stringify() method takes in an object and creates a JSON string from it. The JSON.parse() method parses a string and returns a JavaScript object.

We can combine both of these methods to create a copy of an object in the following way:

1
const user = {
2
    name: "Kingsley",
3
    age: 28,
4
    job: "Web Developer"
5
}
6
7
let clone = JSON.parse(JSON.stringify(user))
8
9
console.log(user)
10
console.log(clone)
11
12
/*

13
{

14
  age: 28,

15
  job: "Web Developer",

16
  name: "Kingsley"

17
}

18
{

19
  age: 28,

20
  job: "Web Developer",

21
  name: "Kingsley"

22
}

23
*/

When the copy object is mutated, the original object stays the same:

1
clone.age = 32
2
3
console.log(user)
4
console.log(clone)
5
6
/*

7
{

8
  age: 28,

9
  job: "Web Developer",

10
  name: "Kingsley"

11
}

12
{

13
  age: 32,

14
  job: "Web Developer",

15
  name: "Kingsley"

16
}

17
*/

However, there is one caveat to using this approach: JSON.stringify() does not copy functions.

Suppose we have a method in our object user called incrementAge:

1
const user = {
2
    name: "Kingsley",
3
    age: 28,
4
    job: "Web Developer",
5
    incrementAge: function() {
6
  	  this.age++
7
    }
8
}

The function will not be available in the copied object. Thus, this method achieves deep copy only if there is no function within the object.

Copy an Object With Object.assign()

Before ES6, Object.assign() was the most popular way to deep copy an object.

1
const user = {
2
    name: "Kingsley",
3
    age: 28,
4
    job: "Web Developer",
5
    incrementAge: function() {
6
  	  this.age++
7
    }
8
}
9
10
let clone = Object.assign({}, user) // Copies user into clone

Object.assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.

1
clone.age = 32
2
3
console.log(user)
4
console.log(clone)
5
6
/*

7
{

8
     age: 28,

9
     incrementAge: function() {

10
       this.age++

11
     },

12
     job: "Web Developer",

13
     name: "Kingsley"

14
}

15
{

16
     age: 32,

17
     incrementAge: function() {

18
       this.age++

19
     },

20
     job: "Web Developer",

21
     name: "Kingsley"

22
}

23
*/

However, one thing to remember about Object.assign() is that the method only performs a partial deep copy on objects.

To understand what that means, let's consider the following:

1
const user = {
2
    name: "Kingsley",
3
    age: 28,
4
    job: "Web Developer",
5
    location: {
6
      city: "Lagos",
7
    }
8
}
9
10
const clone = Object.assign({}, user)

As observed, we added the location property and passed an object as its value. Now we have a more complex structure that contains a nested object. 

Whenever we mutate a property within the nested object (in clone), it will also mutate the same property in the original object (users). Let's take a look:

1
clone.age = 32
2
clone.location.city = "New York"
3
4
5
console.log(user)
6
console.log(clone)
7
8
/*

9
{

10
  age: 28,

11
  job: "Web Developer",

12
  location: {

13
    city: "New York"

14
  },

15
  name: "Kingsley"

16
}

17


18
{

19
  age: 32,

20
  job: "Web Developer",

21
  location: {

22
    city: "New York"

23
  },

24
  name: "Kingsley"

25
}

26
*/

While the age property in the original object remained untouched, the city property was mutated by the reassignment operation.

Hence, the Object.assign() method should be used to deep copy objects that have no nested objects. 

The Best Way to Deep Copy in JavaScript: The Spread Operator

Another way to deep copy objects in JavaScript is with the ES6 spread operator. Using the three dots (...) collects all values on the original object into another object.

1
const user = {
2
    name: "Kingsley",
3
    age: 28,
4
    job: "Web Developer"
5
}
6
7
const clone = {...user}
8
9
console.log(clone);
10
11
/*

12
{

13
  age: 28,

14
  job: "Web Developer",

15
  name: "Kingsley"

16
}

17
*/

However, much like with Object.assign(), the spread operator only makes a partial copy. So any object with a nested object will not be deep copied.

To make a complete deep copy with the spread operator, we'll have to write some additional code.

Consider the same user object but with a nested object:

1
let user = {
2
    name: "Kingsley",
3
    age: 28,
4
    job: "Web Developer",
5
    location: {
6
        city: "Lagos",
7
    }
8
}
9
10
let clone = {...user}

To avoid mutating the original object, which is user, we must spread the copy object before making direct changes to any of its properties. For any nested object, we must also spread that sub-object before making changes to any of its properties:

1
clone = {
2
    ...clone,
3
  age: 32,
4
  location: {
5
  	...clone.location,
6
    city: "New York"
7
  }
8
}

Here, we mutated age, which is a top-level property in clone, and city, which is a sub-property.

This time, the spread operation will give a complete deep copy wherein the original object will be unaffected by any mutation on the copy (clone).

1
console.log(user)
2
console.log(clone)
3
4
/*

5
{

6
  age: 28,

7
  job: "Web Developer",

8
  location: {

9
    city: "Lagos"

10
  },

11
  name: "Kingsley"

12
}

13


14
{

15
  age: 32,

16
  job: "Web Developer",

17
  location: {

18
    city: "New York"

19
  },

20
  name: "Kingsley"

21
}

22
*/

Use Lodash cloneDeep() for Deep Copying

Lodash also provides a utility method _.cloneDeep() for deep cloning of objects in JavaScript.  Read more about the method.

Conclusion

As you've seen, there are a number of ways to copy a variable in JavaScript. None of them is perfect for every occasion, so you'll have to be careful to choose the best method for each situation.

To review, here are the methods and their pros and cons.

Method Pros Cons
shallow copy with = clear and direct, the default only shallow copies objects
JSON.stringify() and JSON.parse() deep copies nested objects doesn't copy functions
Object.assign() copies the immediate members of an object—including functions doesn't deep copy nested objects
the ... spread operator simple syntax, the preferred way to copy an object doesn't deep copy nested objects
Lodash cloneDeep() clones nested objects including functions adds an external dependency to your project
Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.