Unmodifiable array in JavaScript
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let arr = [1, 2, 3]; // make the array unmodifiable Object.freeze(arr); // this will not work arr[0] = 4; console.log(arr); // array remained unchanged - [1, 2, 3] // this will throw an error try { arr.push(5); } catch (e) { // TypeError: Cannot add property 3, object is not extensible console.log(e.name + ': ' + e.message); } |
However, it does not prevents the array from being reassigned to a different value. i.e., changing its reference.
|
1 2 3 4 5 6 7 8 |
let arr = [1, 2, 3]; // make the array unmodifiable Object.freeze(arr); // this will work arr = [6, 7, 8]; console.log(arr); // [6, 7, 8] |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
const arr = [1, 2, 3]; // this will throw an error try { arr = [6, 7, 8]; } catch (e) { // TypeError: Assignment to constant variable. console.log(e.name + ': ' + e.message); } // this will work arr[0] = 4; console.log(arr); // [4, 2, 3] |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const arr = [1, 2, 3]; // make the array unmodifiable Object.freeze(arr); // this will not work arr[0] = 4; console.log(arr); // [1, 2, 3] // this will throw an error try { arr.push(5); } catch (e) { // TypeError: Cannot add property 3, object is not extensible console.log(e.name + ': ' + e.message); } // this will throw an error try { arr = [6, 7, 8]; } catch (e) { // TypeError: Assignment to constant variable. console.log(e.name + ': ' + e.message); } console.log(arr); // [1, 2, 3] |
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:
|
1 2 3 4 5 6 7 8 |
const arr = [1, [2, 3]]; // make the array unmodifiable Object.freeze(arr); // this will work arr[1][0] = 4; console.log(arr); // [1, [4, 3]] |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
let arr = [1, [2, 3, 4], [5, 6]]; // a custom function that can create an unmodifiable array function freezeArray(input) { // if the input is not an array, return it as it is if (!Array.isArray(input)) { return input; } // otherwise, map each element to a frozen value and freeze the whole array return Object.freeze(input.map(freezeArray)); } // create an unmodifiable array let frozenArr = freezeArray(arr); // this will not work frozenArr[0] = 7; // this will not work either frozenArr[1][0] = 8; // this will also not work frozenArr[2][1] = 9; console.log(arr); // [1, [2, 3, 4], [5, 6]] |
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
|
1 2 3 4 5 6 7 8 |
// using Immutable.js const { List } = require('immutable'); const arr1 = List([1, 2, 3]); const newArr1 = arr1.push(4); console.log(newArr1.toArray()); // [1, 2, 3, 4] console.log(arr1.toArray()); // [1, 2, 3] |
Immer
|
1 2 3 4 5 6 7 8 9 10 11 12 |
// using Immer const { produce } = require('immer'); const arr2 = [1, 2, 3]; const newArr2 = produce(arr2, draft => { draft.push(4); draft[0] = 0; }); console.log(newArr2); // [0, 2, 3, 4] console.log(arr2); // [1, 2, 3] |
That’s all about creating an unmodifiable array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)