This post will discuss how to create an unmodifiable array in JavaScript.

An unmodifiable or immutable array is an array that cannot be changed or mutated after it is created. There are several ways to create an unmodifiable array in JavaScript. Here are some of the possible functions:

1. Using Object.freeze() function

The Object.freeze() function prevents any changes to an existing array, such as adding, deleting, or modifying its elements or properties. This function works on both arrays and objects, and it returns the same array or object that was passed as an argument. Here’s an example:

Download  Run Code

 
However, it does not prevents the array from being reassigned to a different value. i.e., changing its reference.

Download  Run Code

2. Using const keyword

We can use the const keyword to declare an array in JavaScript that cannot be reassigned to a different value, but we can still modify the elements of the array. Here’s an example:

Download  Run Code

 
However, the const keyword does not make the array immutable, it only makes the reference to the array constant. That means it does not prevent the array from being mutated by other functions, such as push(), pop(), or splice(). To make the array truly unmodifiable, we need to combine the const keyword with the Object.freeze() function. Here’s an example:

Download  Run Code

 
Note that this approach will not work when the array contains another array as an element i.e. nested array or a multidimensional array. Here’s an example:

Download  Run Code

3. Using a custom function

This function defines a custom function that can create an unmodifiable array by copying the elements of an existing array and freezing them recursively. The function uses a base case to check if the input is an array or not, and then uses the Array.map() function and the Object.freeze() function to create a new frozen array. This has advantage over the above functions as it works for the multidimensional arrays. Here’s an example:

Download  Run Code

4. Using Immutable.js or Immer library

If we want to create an unmodifiable array that cannot be changed at all, we can also use a library or a framework that provides immutable data structures. For example, we can use Immutable.js or Immer library to create and manipulate immutable arrays and objects in JavaScript. These libraries offer various functions and features to work with immutable data, such as creating persistent collections, performing deep copies, applying updates, and more. Here’s an example:

Immutable.js


Download Code

Immer


Download Code

That’s all about creating an unmodifiable array in JavaScript.