This post will discuss how to create an immutable map in JavaScript.

An immutable map is a data structure that stores key-value pairs, where each key is unique and can be any type of value, and the map cannot be modified after it is created. Immutable maps have some advantages, such as preventing accidental mutations, enabling referential equality, and facilitating functional programming. JavaScript does not have a built-in immutable map type, but there are several ways to create and use immutable maps in JavaScript using third-party libraries or custom implementations.

1. Using Object.freeze() function

The Object.freeze() is a built-in function that prevents any changes to an object, such as adding, deleting, or modifying its properties. It also prevents the object’s prototype from being changed. The function returns the same object that was passed as an argument. However, this function only works on the object itself, not on its nested properties. If the object contains other objects, arrays, or maps as values, they can still be modified unless they are also frozen. For example:

Download  Run Code

2. Using Immutable.js library

There are some third-party libraries that provide functions for creating and manipulating immutable maps in JavaScript. For example, Immutable.js is a library that provides persistent immutable collections, such as List, Map, Set, etc. Immutable.js maps are implemented using hash array mapped tries, which allow for fast and efficient operations. They are unmodifiable by design, and any attempt to modify them will return a new map instead of mutating the original one. We can use the set(), delete(), merge(), and other functions to perform immutable updates on the map and return a new map. The following code illustrates this:

Download Code

3. Using immer library

The immer is another popular library that allows us to create and update immutable data structures using a mutable API. We can use the produce() function to create a new immutable map from an existing map or an object. We can also use the draft parameter to modify the map inside the produce() function and return a new immutable map. The following code illustrates this:

Download Code

 
Immer library allows us to create the next immutable state by mutating the current one. Immer uses proxies to track the changes made to a draft state, and then produces a new immutable state based on those changes.

That’s all about creating immutable map in JavaScript.