Immutability in javascript

Ajay Kumar
2 min readJan 2, 2021

In Javascript, arrays and objects are not immutable, i.e., when you clone a object, it will not create a new object, it will create a reference to existing object.

For example,

const person = {name : "Javascript", age: 20 }
console.log(person)
const person1 = person
person1.name= "java"
console.log(person1)
console.log(person)

Output:

 {name: "Javascript", age: "20"}name: "java", age: "20"}
{name: "java", age: "20"}

From the above example.

in 3rd step,

const person1 = person

I have cloned person object into person1 object

In the 4th step, i have tried to change one of the property of the object

person1.name = "java"

When i have tried to print the properties of 2 objects (person and person1), both of their properties seems to be similar.

name: "java", age: "20"}
{name: "java", age: "20"}

since person1 is not a different object, (it internally is a reference of person object), changing person1 object effected person object.

In order to create mutable objects in javascript, i will introduce you to a concept called immer library

To use this immer library in your project, use npm tool

npm install immer

and use immer as

import { produce } from "immer";const person = {name : "javascript", age : "22"}console.log(person)
function getClone(person)
{
return produce( person, clonePerson => {
clonePerson.name = "java",
clonePerson.age = "90";
});
}
let clonedPerson = getClone(person);
console.log(clonedPerson)
console.log(person)

output:

{name: "javascript", age: "22"}
{name: "java", age: "90"}
{name: "javascript", age: "22"}

Here, you can see that original object is not effected by making changes in the cloned object.

Now, let us study getClone() function in detail:

function getClone(person)
{
return produce( person, clonePerson => {
clonePerson.name = "java",
clonePerson.age = "90";
});
}

produce method takes 2 arguments,

a. existing object from where we are supposed to copy data

b. new object to which we are supposed to copy to

once done, produce will create a new object and returns it, (clonePerson object in our case)

--

--