What is immutable.js?
immutable.js is a library of Javascript that is used to support immutable data types.
An immutable datatype is a data type whose value cannot be changed after it is created.
Datatypes
Immutable data types supported by immutable.js are:
- List
- Stack
- Map
- Set
- Ordered map
- Ordered set
- Record
Importing data types
Immutable data types are imported from immutable.js as shown below:
import { datatype } from 'immutable';
datatype: The immutable data type to be imported.
For example, the immutable data type List can be imported as:
import { List } from 'immutable';
fromJS() and toJS()
- The
fromJS()method converts normal Javascript objects to immutable. - The
toJS()method converts immutable Javascript objects back to normal.
Examples
Example 1
Consider the code snippet below, which demonstrates the use of the immutable.js library:
import { isImmutable, List } from 'immutable';const obj1 = ['a', 'b', 'c'];console.log("obj1 is mutable: ",isImmutable(obj1));let obj2 = List(['a', 'b', 'c']);console.log("obj2 is mutable: ",isImmutable(obj2));
Explanation
- A list
obj1is declared in line 3. TheisImmutable()method is called onobj1and checks whether the object is immutable. TheisImmutable()method returns false forobj1, which means thatobj1is not immutable. - A list
obj2is declared in line 6 usingListimported fromimmutable.js. TheisImmutable()method is called onobj2and checks whether the object is immutable. TheisImmutable()method returns true forobj2, which means thatobj2is immutable.
Example 2
Consider the code snippet below, which demonstrates the use of fromJS() and toJS():
import { isImmutable, List, fromJS} from 'immutable';let obj1 = List(['a', 'b', 'c']);console.log("obj1 is mutable: ",isImmutable(obj1));const obj2 = fromJS(obj1);console.log("obj2 is mutable: ",isImmutable(obj2));const obj3 = obj2.toJS();console.log("obj3 is mutable: ",isImmutable(obj3));
Explanation
-
An immutable list
obj1is declared in line 3. -
The
fromJS()method is used in line 6 to create another immutable listobj2that has the same data asobj1. TheisImmutable()method is called onobj2to check if it is immutable. TheisImmutable()method returns true forobj2, which means thatobj2is immutable. -
The
toJS()method is used in line 9 and converts the immutable objectobj2to mutable and assigns itobj3. TheisImmutable()method is called onobj3to check if it is immutable. TheisImmutable()method returns false forobj3, which means thatobj3is not immutable.
Free Resources