JavaScript

How to Deep Clone Objects in JavaScript

JavaScript is entirely based on objects, everything in JavaScript is an object. Arrays are objects, Strings are objects and objects are objects. When you are working with objects or arrays, sometimes there comes a need to copy or clone an array or object.

There are two types of clones of objects\arrays, one of them being shallow clones and the other one being deep clones.

To create deep clones in vanilla JavaScript, we need to use a combination of JSON parse() function and JSON stringify() function. In this post, we are going to discuss what are shallow clones and deep clones, how to make clones in JavaScript, and how to make deep clones.

Shallow Clones vs Deep Clones

Whenever an array\object containing another array\object inside it is copied from one variable to another variable, the elements of that array\object are not copied; rather a reference pointer is copied to the new variable which points at the old variable. Such copies are known as shallow copies or shallow clones

Whereas, when the elements of an array\object are copied directly (not their reference pointer) to a new variable along with the nested array\object then that copy is known as deep clones or deep copies.

Explanation with JavaScript Code

These are advanced JavaScript concepts, that is why we will use coding examples to demonstrate the difference between shallow cloning, and deep cloning. To get started, create an array containing various elements using the following line of code:

var originalArray = [true, false, 2, "Google", undefined];

Now, there are two ways of cloning this array:

  • By using the slice method
  • By using the spread operator

To create a clone using the slice method use the following line:

var clone1 = originalArray.slice(0);

And to create a clone using the spread operator use the following line:

var clone2 = [...originalArray];

To test if our elements were copied or not we can use the console log function to print out the original array as well as both of our clones:

console.log(originalArray);

console.log(clone1);

console.log(clone2);

We get the following output on our console:

To prove these are actual clones, and not references of the original array passed inside these variables we are going to make some changes in the clones and check if these changes affect the original array or not.

clone1[0] = 1;

clone2[1] = "Hello";

Print all the arrays onto the console once again to examine the changes with the following lines:

console.log(originalArray);

console.log(clone1);

console.log(clone2);

You will observe the following output:

As you can see, changes in the clone arrays didn’t affect the original array which means that other arrays didn’t copy the reference of the original array.

Shallow clones verification

We have seen how to clone simple arrays, but what if we have an array or object that contains another array inside it, consider the following array:

var originalArray = [["Google"]];

As you can see, we have an array inside another array, let’s try to make a clone of this array using the slice method that we have already used in the above example:

var clone = originalArray.slice(0);

We have made a clone of this array in the variable “clone”, print out both of these arrays using the console log function:

console.log(originalArray[0]);

console.log(clone[0]);

You should see the following result on the console of your screen:

Let’s try making some changes in the cloned array with the following line of code:

clone[0].push("Maps");

This should make changes in only the “clone” array and not in the original array, but this is where things get interesting. Print out both the arrays using the console log function:

console.log(originalArray[0]);

console.log(clone[0]);

You should see the following result on your console:

You can easily observe from the image above that changes in the cloned array caused changes in the original array. This means that if our object\array contains object\arrays then the cloning passes reference to the nested objects thus creating a shallow clone.

Deep Cloning in Vanilla JavaScript

Phew… That was a lot of stuff just to explain one concept of shallow clones but then again, these are advanced-level concepts. To make deep clones using JavaScript multiple methods are available but most of them require NodeJs. To make deep clones in vanilla JavaScript, you need to use a combination of the JSON parse() function and the JSON stringify() function. Create an array with a nested array inside it with the following line of code:

var originalArray = [["Google"]];

Use a combination of JSON parse and JSON stringify() with the following line:

var deepClone = JSON.parse(JSON.stringify(originalArray));

Now, that we have made our clone we need to verify it by printing it out onto the console by using the console log function:

console.log(clone[0]);

You will get the following result on the console:

Now, let’s try changing the elements of the cloned array using the following line:

deepClone[0].push("Maps");

The last thing that is left is to observe both the arrays on the console to determine whether changing the cloned array changed the original array or not:

console.log(originalArray[0]);

console.log(deepClone[0]);

You will get the following result on your console:

In the above image, you can observe that changes in the cloned array didn’t cause any change in the original array. This means that the nested arrays\objects were also copied rather than their reference being passed to the new variable, and this is why such clones are called the deep clones.

Conclusion

Deep clones in vanilla JavaScript are made by using a combination of JSON parse() function and JSON stringify() function when parsing an object\array in a new variable. Everything in javascript is an object, and when we are trying to copy nested objects, their reference to the pointer is copied to the new variable rather than copying the elements of the nested arrays\objects. When reference of an object is passed to a new object change in the new object cause changes in the old object as well which is not very efficient. This is the reason why javascript added a way of creating deep clones.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.