Immutability in JavaScript

Hello World 🌏 !!! In my previous article I’ve explained 3 ways to not copy JavaScript objects. In this article I’ll explain how can we copy objects in JavaScript and the concept of immutability.

Mutable = Can change
Immutable= Can’t be changed

So, first let’s understand why this copy thing is complicated in JavaScript?
The short answer is because JavaScript is a mutable language.

In JavaScript only primitive values (strings, numbers, BigInts, boolean. undefined, null ) are Immutable. We can’t change them.

But wait, consider following code:

Aren’t we changing the a and b ? No. we aren’t. In the above code a and b are not values. They are variables.

Variables are not values. Variable points to values.

So in above code, we are just changing the variable reference not the value.
To get more clarity, consider this code.

Here we are trying to change the values of a and b . The effect of the code is based on whether we have strict mode turned on or not.
If strict mode is on then we get an error. Else the effect of code is nothing.

Now we’ve understood that primitives are Immutable. Now let’s see what about objects and arrays.

In JavaScript Object and Arrays are mutable. That means we can change them after there creation. To understand this:

In this code we are able to mutate the object and arrays. Which can lead to data in-consistency and may introduce many bugs in code. Because we may pass an object to a function and may be that function unknowingly mutates the passed object.

So now we are clear about the problems, now lets discuss about the good parts of immutability and ways to achieve it.

Immutability helps us in:
1. Giving us more granular control over our data
2. we can achieve Undo/Redo and Rollback
3. Performance of our app increase as comparison of values take less time as compared to references.

Now let us see how can we achieve the Immutability in JavaScript.

Unfortunately, till now, there is no native way of doing it. There is one experimental functionality called Structured Cloning is available in V8, but that is only for node.

In JavaScript we can use few most popular libraries in order solve the problem of mutability.

  1. lodash
    we can use lodash's cloneDeep method to make copies of our object.

If the size of lodash is an issue, we have several ways to solve this:
Import cloneDeep like this (If you are only using cloneDeep method)

2. lodash.cloneDeep

3. just-clone Zero Dependency Library — Size ~1KB

3. Immutable.JS — Developed by Facebook developers.

So, that’s all about Immutability in JavaScript. I hope you have got an idea about Immutability. You may swim in ocean of JavaScript to understand this concept more deeply.