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.
Immutable data types supported by immutable.js
are:
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()
method converts normal Javascript objects to immutable.toJS()
method converts immutable Javascript objects back to normal.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));
obj1
is declared in line 3. The isImmutable()
method is called on obj1
and checks whether the object is immutable. The isImmutable()
method returns false for obj1
, which means that obj1
is not immutable.obj2
is declared in line 6 using List
imported from immutable.js
. The isImmutable()
method is called on obj2
and checks whether the object is immutable. The isImmutable()
method returns true for obj2
, which means that obj2
is immutable.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));
An immutable list obj1
is declared in line 3.
The fromJS()
method is used in line 6 to create another immutable list obj2
that has the same data as obj1
. The isImmutable()
method is called on obj2
to check if it is immutable. The isImmutable()
method returns true for obj2
, which means that obj2
is immutable.
The toJS()
method is used in line 9 and converts the immutable object obj2
to mutable and assigns it obj3
.
The isImmutable()
method is called on obj3
to check if it is immutable. The isImmutable()
method returns false for obj3
, which means that obj3
is not immutable.
Free Resources