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

An immutable array is an array that cannot be modified or changed after it is created. This means that any operation that would normally change the array, such as adding, removing, or sorting elements, will not affect the original array. Immutable arrays can help prevent accidental mutations, bugs, and side effects in the code. There are different ways to create and work with immutable arrays in JavaScript, such as:

1. Using Object.freeze() function

We can use the Object.freeze() function to prevent any changes to an existing array, such as adding, removing, or updating elements. It also prevents changes to the array’s prototype and properties. This will make the array read-only and throw an error if we try to modify it. This function can be used to create an immutable array by passing the array as an argument. Here’s an example:

Download  Run Code

 
This function is simple and effective, but it has some limitations. This function only freezes the array itself, not the elements inside it. If the elements are objects or arrays, they can still be modified, unless they are also frozen. It also does not prevent the array from being reassigned to a different value and it may not be supported by older browsers. However, we can easily handle the array from being reassigned to a different value by declaring the array using the const keyword. For example:

Download  Run Code

2. Using third-party libraries

Another option is to use third-party JavaScript libraries that provides various immutable data structures and functions, such as Immutable.js, Ramda.js, Lodash.js, etc. These libraries often have their own implementations of arrays that are immutable by default, or provide functions to create immutable copies of arrays.

Download Code

 
These libraries are convenient and powerful, as they leverages the features and benefits of functional programming in JavaScript, such as immutability, purity, composability, etc. However, it also requires adding an external dependency to the project, which may increase the size and complexity of the codebase.

3. Using ExtendedArray constructor

Finally, we can create a custom array object that inherits from the built-in Array prototype, but overrides some of the methods that mutate the original array, such as push, pop, reverse, sort, splice, etc. It also provides a utility function to create an immutable extended array that cannot call any of the impure functions. For example:

Download  Run Code

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