Cloning objects in JavaScript. Looking under the hood of reference and primitive types.

There are two types of clones in JavaScript: deep, and shallow. To fully understand the difference, we need to dive deeper into how the interpreter treats different types of variables. Let’s go!

Primitive types

  • null
  • undefined
  • boolean
  • number
  • string
  • symbol

These are the types that are immutable. Some of you might be surprised – we can, in fact, extend a string for example. Let me use some good old string concatenation to better illustrate what I have in mind.

What happens here is that in the second line, we assign a brand new string to the variable named fullName, even if it might seem like modifying an existing one. Same goes for other primitive types. That is the reason why I used let instead of const here.
Using the latter would result in:

Uncaught TypeError: Assignment to constant variable.

Another thing to keep in mind is that primitive types can’t have any methods or properties. But can they not, really?

It is a valid piece of code thanks to the fact that almost all primitive types (except for null and undefined) have an object that wraps around the primitive value. Let me do a little bit of trickery to prove it.

The wrapper for that particular variable of primitive type is not kept for long though: as soon as the work is done, it is gone.
A way to observe it is to try to define a property for the string and assign a value to it.

Fire up the console and experiment a little.

Reference type

The only reference type is an object – it can have properties and methods. Arrays are also objects! They are just an instance of an Array and inherit from Array.prototype. Beware of some rookie mistakes!

The crucial concept to grasp in the context of cloning objects is how the references are handled.

As you can see, changing properties of Dorothy caused them to change also for John – this is because they are both a reference
to the same object!

Shallow clone

Situation like the one described above often creates a need to make a clone. The most basic one you can do is called a shallow clone.
There are a few options here. My personal favourite includes using a spread operator.

As you can see, changing the firstName property for Dorothy no longer messes with John. A clone like that is called shallow
for a reason, though – as you can see, it only cloned the first layer of the object – that means that all of the clones share the same instance of the city property.

There is a way to prevent mutating our template a little using Object.seal and Object.freeze.
The first one will prevent adding and removing any properties from the object (throwing an error), while the latter will also prevent modifying the existing properties. Keep in mind that it will result in an error if you are in strict mode. If you’re not, it will still prevent the mutation, though.
Unfortunately, it is shallow and won’t prevent mutating any object properties – it means that in our userTemplate, we will still be able to change properties of the city, even if its parent is frozen.

Cloning with a spread operator creates a new object with all of the properties of the old one (methods included). It does not copy the chain of Prototypes though, so watch out!

A very similar way to create a clone is to use Object.assign()

This function copies all of the properties of the old object straight to the new object and returns it. It won’t copy the chain of Prototypes either.
Just keep in mind that both of these solutions require ES6. Making a shallow copy without it will require writing a polyfill, or using one of many libraries such as lodash that have this functionality.

Deep clone

This is where things get a little trickier. The most basic way to create a deep clone is to use a built-in JSON parser.

There are a lot of drawbacks here, though. As you may have guessed already, it won’t copy the chain of Prototypes either. To make things worse, it won’t even copy any methods along the way – they are not included in the JSON format after all – this might give you quite a headache.

If that’s fine by you, that’s great.
If not, you will once again depend on external libraries or will need to write additional logic yourself. In another article, I will walk you through writing such function yourself. We will also publish it on Node Package Manager (NPM) registry, so stay tuned!