JavaScript allows us three different ways to copy an object. The way we choose to copy an object depends on the version of JavaScript were using and if it’s a deep and shallow object

Shallow Objects

If we need to copy an object thats shallow then we have two options. I’ll show the one that has the most browser compatibility first, and then the new one for ECMAScript 2020.

Spread Syntax

The spread operator allows us to iterate over any iterable (array, map, set, string) and as of 2018 we can iterate over objects although their not technically an iterable like map. We use the spread operator by three dots before the iterable like so …anIterable. Here’s an example of all except object which we will cover in a bit.

Then we can pass the spread iterable into anything that requires 0+ arguments like a function parameter or a data value. When we assign an object literal in Javascript it too can take 0+ arguments


The Object.Assign() is a new addition we got in 2019 that does the same object copying

Deep Copying

Now the two before mentioned options will be perfect for most situations. However, there will be times when an object property references another property, or a nested object. When you make a shallow copy it just makes a copy of the data, but it keeps a pointer to any circular references or nested objects. However, by using JSON.parse(JSON.stringify(object)) we can get around this

Now if this works as expected our tired Employee should not have changed all the objects except the animalTypeJSON object

Perfect our tired employee wasn’t able to change the hawk animal class to mammal