Immutability in javascript (immutable js)

What is it?

Immutability is the concept of never changing a value after it has been created. So if a value needs to change, we create a new one rather than editing the existing value.

Immutability in JS

Some types in javascript are immutable by default such as string, number, boolean, undefined, null. The types that aren’t are objects, arrays and functions.

How to achieve immutability in JS?

Example immutability for object.

var user = {
name: ‘joe’
};

Traditional way to change a value in an object.

user.name = ‘jane’;

Immutable way to change a value in an object, (shallow only, use lodash merge for deep).

user = Object.assign({}, user, {name: ‘jane’});

Or

We can freeze the object, (shallow only).

Object.freeze(user);
user.name = ‘jane’; //throw in strict mode

Example immutability for arrays.

var users = [‘joe’, ‘jane’, ‘jack’];

Traditional way to add a value to an array.

users.push(’tom’);

Immutable way to add a value to an array.

users = […users, ’tom’];

Having functions that return new data structures without effecting the source passed to a function are known as pure functions. These are a key functional programming styles.

Advantages to immutable data structures

Single place for changes

In the above example you would simply write a function that ‘updatesUser’ and accepts a user object. This means that when the state of the user object changes there is a single place to look. If the user object was not immutable we could call ‘user.name=…’ from anywhere in the codebase and it would be more difficult to find out where a change to the user object was made.

Performance

Particularly in relation to react/redux when deciding whether to re-render the DOM, the said liberties will check if the user object has changed. If the user object is not immutable it will need to loop over every property and its children to see if there is a change from the previous user object. If the user object is immutable it can simply check if the user object and the previous user object is referencing the same object in memory and if it is not, the object has changed. This is a far less expensive operation to perform.

History/time travel/undo

When the user object is immutable you have the previous complete user object as it was before the change, (name update), occurred. This makes it possible to memorise these previous states and look back on them if required. This means in a data driven application you can take the state form three or four actions ago and travel back in time, undoing actions as required. Most immutable data structure algorithms do not store whole copies of previous objects, but only that of whats changed, (see DAC below).

DAC, (Directed, Acyclic, Graph)

Way to share structures so that when a node, (property in a nested object structure), changes, only the necessary parent objects with the new references are changes and the rest of the child nodes that have not changed can be shared between states. This reduces size as not all shared linked objects are cloned.

Immutable JS library

Provides functions to help create immutable data structures and lists. The main ones are Map, Set and List. Use .is for value equality instead of === which uses reference equality. You can still filter over immutable lists using filter, map and reduce just like you would a normal array. To convert immutable object back to none immutable objects you can use .toObject/.toArray, (shallow), .toJS (deep). To convert to none immutable data structure to an immutable one you can use .fromJS which will convert arrays to immutable lists and objects to immutable maps. You can .mergeDeep, (similar to loads .merge), and .getIn, (similar to loads .get) and .updateIn. It has a function called .seq which will lazily evaluate chained iterable functions on a collection of data. Mutations can be batched if performance becomes an issue with heavy data loads with .withMutations.

References

https://www.youtube.com/watch?v=I7IdS-PbEgI&feature=youtu.be
https://facebook.github.io/immutable-js/
https://auth0.com/blog/intro-to-immutable-js/
http://www.zsoltnagy.eu/introduction-to-immutable-js/