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

Miguel Angel Muñoz
Version 1
Published in
2 min readJul 4, 2022
Photo by Phil Shaw on Unsplash

How many times did you try to clone an object in Javascript and the output wasn’t exactly what you expected? In this article, we will explain the basic 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: means that only the first level of the object is copied. Deeper levels are referenced.
  • Deep copy: means that all levels of the object are copied. This is a true copy of the object.

Shallow copy

A shallow copy can be achieved using the spread operator () or using Object.assign():

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 in a deeper level, the original property is also updated. This happens because, in this case, deeper levels are referenced, not copied.

Deep copy

A deep copy can be achieved using JSON.parse() + JSON.stringify():

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 in a deeper level, the original property is neither updated. This happens because, in this case, deeper levels are also copied.

Performance

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. So, which option should I use?

  • If the depth of your object is equal to one, use a shallow copy.
  • If the depth of your object is bigger than one, use a deep copy.

Happy coding!

About the Author:

Miguel Munoz is a Principal Software Engineer at Version 1. Follow our Medium account for more content.

--

--

Miguel Angel Muñoz
Version 1

Principal Software Engineer @ Version 1. Front-end/Javascript enthusiast 💻 & Video Game lover 🎮 . I spend my free time learning 📝 or playing 👾.