Efficient Way to Deep Copy Objects And Nested Objects in JavaScript

Suchitkore
3 min readSep 14, 2023

--

You will learn how to deep copy not only normal objects but nested objects and objects containing function.

Object Deep Copy in JavaScript

Deep Copy:

A Deep Copy is a copy that creates a new object with a new memory location to store the object and all of its properties. You can see it in the image. It means that if you make changes in the cloned object, it will not affect the original object. Whenever we are cloning arrays and objects in JavaScript to avoid data loss.

There are three ways to deep copy of object

  1. Using Spread Operator ({…})
  2. Using Object.assign() method
  3. Using Json.Parse() and Json.Stringify()

Using Spread Operator:

Normal object copy using Spread Operator

As you can see, You can clone normal object properties by using the Spread operator but we are unable to Deep clone nested object properties by using the Spread Operator. Let us see in the next image….

Nested Object copy using Spread Operator

Key Note: We are able to Deep Copy a normal object using the spread operator, but not able to Deep Copy a nested object. It means when we change the property of the nested object of the cloned object then it will change the original object property also. It means that for nested object copy using Spread Operator behave like Shallow Copy.

Using Object.assign() Method:

Normal Obect copy using Object.assign()

As you can see, You can clone normal object properties by using the Object.assign() but we are unable to Deep clone nested object properties by using the Object.assign(). Let us see in the next image….

Nested Object copy using Object.assign()

Key Note: We are able to Deep Copy a normal object using the Object.assign(), but not able to Deep Copy a nested object. It means when we change the property of the nested object of the cloned object then it will change the original object property also. It means that for nested object copy using Object.assign() behaves like Shallow Copy.

Using Json.parse() and Json.Stringify()

This is the only way to do a Deep Copy of any normal and Nested Objects. You can see it in the below image…

Object Copy using Json.parse() and Json.stringify()

How to Deep Clone an Object containing function in Javascript?

Copy of an Object containing function using Spread Operator, Object.assign(), Json.parse() and Json.stringify()

As you can see in the above image, Deep Copy of an object containing function can be possible using Spread Operator and Object.assign() method only. not by using Json.parse() and Json.stringify().

--

--