Cloning an Object in Javascript: Shallow Copy vs. Deep Copy

Cloning an Object in Javascript: Shallow Copy vs. Deep Copy

·

2 min read

Have you tried to clone an object in Javascript and the output wasn't what you expected? In this article, I will explain the concepts behind cloning to ensure that you always use the right option.

Shallow copy Vs Deep copy

There are two ways to clone an object in Javascript:

  • Shallow Copy:
    A shallow copy creates a new object and copies all the properties of the original object to the new object. However, if the original object contains properties that are objects themselves, only the reference to those objects is copied, not the objects themselves. In other words, only the first level of the object is copied. Deeper levels are referenced.
    A shallow copy can be achieved using the spread operator (…) or using Object. assign.

Let's take a look at an example:

As you can see in this code snippet:

  • After updating a property in the first level of the cloned objects i.e the name property, the original property is not updated.

  • After updating a property in a deeper level, the original property is also updated. This happens because, deeper levels are referenced, not copied.

    • Deep Copy:
      A deep copy creates a new object and copies all the properties of the original object to the new object, including properties that are objects themselves. This means that the new object is completely independent of the original object. In other words, all levels of the object are copied. This is a true copy of the object.
      A deep copy can be achieved using JSON.parse + JSON.stringify.

Let's modify the previous example to create a deep copy:

As you can see in this code snippet:

  • After updating a property in the first level of the cloned objects, the original property is not updated.

  • After updating a property on a deeper level, the original property is neither updated. This happens because deeper levels are also copied.

For obvious reasons, shallow copies are a lot faster than deep copies. But this doesn’t mean that you should always use a shallow copy, because sometimes you will also need a copy of the nested objects.

Happy coding!😊😊