This page looks best with JavaScript enabled

Understand Shallow And Deep Copy In JavaScript

 ·  β˜• 5 min read  ·  ✍️ Adesh

What is shallow copy and deep copy in JavaScript?

In JavaScript, there are two ways to copy the objects. These are the following:

Shallow copy –– When we copy a new object from the old object, then this new object is also pointing towards the same memory reference of the old object. This lowers memory usage as well. Both new and old objects are accessing the same memory location.

For example, a shallow copy makes a copy of the reference to X into Y. So, both the X and Y point to the same memory location.

Deep copy–– Deep copy a new object with a new memory location. This memory location references to this new object and its contents. Since a new memory location is created, it increases memory usage.

For example, a deep copy makes a copy of all the members of X, creates a new memory location for Y and then assigns the copied members to Y. So, both are pointing to different memory locations.

Let’s take an example

Let me explain this by example.

Shallow Copy

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var car = { name: 'Audi', color: 'blue', price: '\$25000'};

var duplicateCar = car;

duplicateCar.color = 'red';

console.log('Original Car');
console.log(car);

console.log('Duplicate Car');
console.log(duplicateCar);

Here is the result.

'Original Car'
{
name:"Audi",
color:"red",
price:"$25000"
}
'Duplicate Car'
{
name:"Audi",
color:"red",
price:"$25000"
}

In this example, we created a car object and copy it into another object duplicateCar using the shallow copy. Now, I changed the color of duplicateCar object to red, then our original car object color also changes to red color. This means that, we are losing the original data as well.

This is how shallow copy works. Here point to be noted that we are not creating two objects, it is only one object with two memory references. So, if we change the value of any object, it will reflect changes in other objects as well.

Sometimes, shallow copy becomes problematic, since we expect the changes only in the copied object, not the original ones. This may lead to an error without your knowledge.

A shallow copy of the object can be done using object.assign() method in javascript.

1
2
3
let obj = { a: 1, b: 2 };
let objCopy = Object.assign({}, obj);
console.log(objCopy); // Result - { a: 1, b: 2 }

We have made a copy of obj. Let’s see if immutability exists:

1
2
3
4
let obj = { a: 1, b: 2 };
let objCopy = Object.assign({}, obj);
console.log(objCopy); // result - { a: 1, b: 2 } objCopy.b = 80;
console.log(objCopy); // result - { a: 1, b: 80 } console.log(obj); // result - { a: 1, b: 2 }

In the code above, we changed the value of the propertyΒ 'b'Β inΒ objCopyΒ object toΒ 89Β and when we log the modifiedΒ objCopyΒ object in the console, the changes only apply toΒ objCopy.

The last line of code checks that theΒ objΒ object is still intact and hasn’t change. This implies that we have successfully created a copy of the source object without any references to it.

Deep Copy

Let’s see how deep copy works. We will now create the same object by using the properties from the original car object.

1
2
3
4
5
var duplicateCar = {
  name: car.name,
  color: car.color,
  price: car.price,
};

This is an example of deep copy. We are assigning each property of car object to properties of duplicateCar object. Now, if you change any property of duplicateCar object, it won’t affect the original car object.

Below is the complete example of creating object using deep copy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var car = { name: "Audi", color: "blue", price: "$25000" };

//var duplicateCar = car;
var duplicateCar = {
  name: car.name,
  color: car.color,
  price: car.price,
};

duplicateCar.color = "red";

console.log("Original Car");
console.log(car);

console.log("Duplicate Car");
console.log(duplicateCar);

I commented on the second line and created duplicateCar using properties assignments.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
'Original Car'
{
name:"Audi",
color:"blue",
price:"$25000"
}
'Duplicate Car'
{
name:"Audi",
color:"red",
price:"$25000"
}

We also changed the color property of duplicateCar object, and there is no change in the original car object.

A deep copy of the object can be done using JSON.parse(JSON.stringify(object));

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let obj = {
  a: 1,
  b: {
    c: 2,
  },
};
let newObj = JSON.parse(JSON.stringify(obj));
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } } (New Object Intact!)

Conclusion

Copying objects in JavaScript can be quite daunting especially if you’re new to JavaScript and don’t know your way around the language. Hopefully this article helped you understand and avoid future pitfalls you may encounter copying objects.

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript

Further Reading

Object Mutation In JavaScript

What Is JavaScript Callback And How Does It Work?

Remove An Item From The Array Using JavaScript Splice()

Add An Item To An Array Using JavaScript Splice()

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect