Immutable array in JavaScript
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let arr = [1, 2, 3, 4]; // freeze the array Object.freeze(arr); // this will throw an error try { arr.push(5); } catch (e) { // TypeError: Cannot add property 4, object is not extensible console.log(e.name + ': ' + e.message); } // this won't impact array arr[0] = 10; arr.length = 0; // the array remained unchanged console.log(arr); // [1, 2, 3, 4] |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const arr = [1, 2, 3, 4]; // freeze the array Object.freeze(arr); // this will throw an error try { arr = [1, 2, 3, 4, 5]; } catch (e) { // TypeError: Assignment to constant variable. console.log(e.name + ': ' + e.message); } // the array remained unchanged console.log(arr); // [1, 2, 3, 4] |
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.
|
1 2 3 4 5 6 7 8 9 10 |
// Using Immutable.js let arr = Immutable.List([1, 2, 3, 4]); // arr is an immutable list // Using Ramda.js let arr = [1, 2, 3, 4]; let newArr = R.clone(arr); // newArr is an immutable copy of arr // Using Lodash.js let arr = [1, 2, 3, 4]; let newArr = _.cloneDeep(arr); // newArr is an immutable copy of arr |
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:
|
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
// Define a custom array constructor function ExtendedArray() { let arr = new Array(...arguments); arr.__proto__ = ExtendedArray.prototype; return arr; } // Inherit from the Array prototype ExtendedArray.prototype = Object.create(Array.prototype); ExtendedArray.prototype.constructor = ExtendedArray; // Override some of the impure functions ExtendedArray.prototype.push = function() { throw new Error("Cannot modify an immutable array"); }; ExtendedArray.prototype.pop = function() { throw new Error("Cannot modify an immutable array"); }; // … and so on for other functions // Define a utility function to create an immutable extended array ExtendedArray.immutableOf = function() { let arr = new ExtendedArray(...arguments); Object.freeze(arr); return arr; }; // Create an immutable extended array const arr = ExtendedArray.immutableOf(1, 2, 3); // arr is now immutable // this will throw an error try { arr.push(4); } catch (e) { // Error: Cannot modify an immutable array console.log(e.name + ': ' + e.message); } // this won't impact array arr[0] = 10; // ExtendedArray(3) [ 1, 2, 3 ] console.log(arr); |
That’s all about creating an immutable 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 :)