Working with Immutable data in JavaScript

We often come across the term immutability or changing data immutably in our programming life. If you are from React background or just have started working on React, then you must have been familiar with this term. So what exactly this immutability means and how it affects our application, let’s take a closer look.

What are mutable and immutable data?

The variables whose value cannot be changed after initialization are immutable whereas mutable data are those whose value can be changed at later time.

Examples of immutable data are Strings and Numbers. When we try to assign a new value to string or number type data, reference is assigned to a new object.

Examples of mutable data are Arrays and Objects. When we try to change values in mutable data, the change applies to all of its references.

Why Immutability Matters?

Let us suppose you are working on an application and you have some data that you don’t expect to be changed at later time. But in somewhere unknowingly someone mutate one of those data with a new value. Then any change in the mutated data can change the original data which will cause a big issue for your application. To avoid that, we should deal with data immutably.

For example, if you are not expected to reassign a variable, then you can declare it with the keyword const instead of var or let.

var id = 512;

id = 160;

let name = "Amitav";

name = "George";

const city = "Bangalore";

city = "Hyderabad"; // TypeError: Assignment to constant variable

In JavaScript both Arrays and Objects are of reference types. That means if you will assign any array or object to a new variable, it will not create a new object instead it will just pass the reference to the original object.

const arr = [20, 40, 80];

Now let’s copy this array to a new variable and make some changes.

const copyArr = arr;

arr.push(120);

console.log(copyArr); // [20, 40, 80, 120]

console.log(arr); // [20, 40, 80, 120]

So here you can see, while we tried to make some changes in the copied array it reflects in the original array. It directly mutated the original array. That means when we tried to copy the array to a new variable, it didn’t create a new array instead it passed a reference to the original array.

Same goes with objects. Let’s create one object.

const person = {name: 'Amitav Mishra', city: 'Bangalore'};

Now let’s copy this object to a new variable and make some changes.

const otherPerson = person;

otherPerson.city = 'Delhi';

console.log(person.city); // Delhi

Here also while we tried to copy the object it simply gave the reference to original object. So to avoid this problem we need to update data immutably by deep cloning objects and arrays.

Using Object.assign()

By using Object.assign() method we can create an exact copy of the array or object data and then we can modify the data immutably.

const person = {name: 'Amitav Mishra', city: 'Bangalore'};

const otherPerson = Object.assign({}, person);

otherPerson.city = 'Delhi';

console.log(person.city); // Bangalore

console.log(otherPerson.city) //Delhi

Here we created an exact clone of person and assigned to otherPerson. So updating the otherPerson object didn’t affect the original person object.

The Object.assign method only works if there is one level of entries present in object. If any nested objects or arrays are present then this method doesn’t work. For nested objects use deep cloning.

Same way we can do for arrays.

const arr = [20, 40, 80];

const copyArr = Object.assign([], arr);

copyArr.push(120);

console.log(arr); //[20, 40, 80]

There are also other ways to clone arrays.

Using slice():

const copyArr = arr.slice(0);

Using spread operator:

const copyArr = [...arr];

References

Leave a Reply

Your email address will not be published. Required fields are marked *