immutable

What is Immutable Data?

Simply data that can not be changed is immutable.

In the example below, we have data array which contains no of hours one employee worked on some specific project.

var hoursWorked = [8, 8, 8, 7, 7, 9, 6, 8, 8, 7];

console.log(hoursWorked);

//op:  [8, 8, 8, 7, 7, 9, 6, 8, 8, 7]

lets check last 5 days of work

var lastFiveDays = hoursWorked.slice(0,5);

console.log(lastFiveDays);

//op: [8, 8, 8, 7, 7] awesome

//let me sort the hourseWorked

var sortedHoursWorked = hoursWorked.sort();

console.log(sortedHoursWorked);

//op:  [6, 7, 7, 7, 8, 8, 8, 8, 8, 9] Perfect

var lastSixDays = hoursWorked.slice(0,6);

console.log(lastSixDays);

//op: [6, 7, 7, 7, 8, 8]  ohh No  [8, 8, 8, 7, 7, 9] expected.

 

As Javascript send reference to functions, there are many chances to change original dataset. So Immutability is so Important in Javascript or any Programming language.

 

In above the example, we have used 2 different methods, slice, and sort.

  1. Slice
    Slice is an immutable way as it did slice the original object and sent the new copy to the lastFiveDays Object. It helped us to regain the original copy of the dataset as well.

 

  1. Sort
    Sort is a mutable way as it sorted the original dataset. It blocked us to make further calculations on the dataset.

 

What are the benefits of Immutability?

According to react documentation.

Easier Undo/Redo and Time Travel
When you are implementing word document in Javascript and you want to give features like redo/ undoes then you need to have different copies at a different time. We need to avoid mutation and should keep the references of older versions as well. just like version control system.

 

Tracking Changes

when you are working on the complex object. In case Object is mutable one step/statement can change the structure or value of the object and later operation may lead incorrect data. Immutable data helps here.

 

Determining When to Re-render in React

This point is regarding when to update the view of your page. If we have different copies of the object we can decide if 2 objects are changed then we will update. We need something to take a decision on otherwise we will keep updating the vie whenever some event has fired.

Looking for React JS Development Company, Hire our dedicated developers!

Thank You!

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.