December 21, 2022
Estimated Post Reading Time ~

What is immutability in JavaScript?

What is immutability in JavaScript?

Immutability is the concept of objects not getting modified after they are created.

In contrast to an immutable object, a mutable object is an object whose state can be modified or changed over time.

In JavaScript, strings and numbers are immutable data types.

This means the strings or numbers cannot be changed after they are created.

For example
let x = 5;
let name = 'John';
name[0] = 'R'; ❌ will not modify 'John'

The value of 5 is always 5, and 'John' is always 'John' and we cannot modify those values.

We can just reassign the variables but not modify the actual values.

Objects in JavaScript are mutable.

An array is an object in JavaScript.

const arr = [1, 2, 3];
arr[0] = 5; // arr → [5, 2, 3]

Objects are non-primitive data types which means they give reference to the objects that are stored in the memory.

Why do we need immutability?
Immutability helps avoid unpredictable results.
Modifying original objects will reflect the changes in all the places they are used.

That's why many libraries/frameworks use the concept of immutability.

e.g., React, Redux

It's a good practice to not modify the objects directly, instead get a copy of the contents of an object and do the operations.

const nums = [1, 2, 3];
const newArr = [...nums];
newArr[0] = 5;

// nums → [1, 2, 3]
// newArr → [5, 2, 3]

That's a quick overview of immutability concept in JavaScript.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.