How to prevent array mutation in JavaScript

Overview

In JavaScript, there are many ways to store data, and one of them is the array. We can store several pieces of data in one place in an array instead of storing them in several spaces using variables.

Unlike strings and variables, arrays are mutable, or easily changed. They can be changed freely, even if we use const in their declaration. Here’s an example:

Console
Array mutation

Explanation

  • Line 1: In the example above, we create an array named myArray and store 7 numbers in it.

  • Line 2: We access the first element of the array using the bracket notation and print the result (1) to the console.

  • Line 3: We access the first element again using the same method in line 2 above and assign it a new value (9).

  • Line 4: We access the first element again and print it to the console. The console now prints 9, which is the new value assigned.

Despite how myArray was declared with const, the elements were still changed freely. This shows that arrays are mutable.

The Object.freeze() function

To prevent the mutation of arrays and objects, JavaScript provides a function Object.freeze() which prevents data from being changed easily. Any attempt to change the data of objects and arrays will be rejected and the original values will be used any time they are accessed across our code. Here’s an example:

Console
Mutation prevention

Explanation

  • Line 1: We declare an array with const and assign it seven elements.

  • Line 2: We print the value of the third element of the array to the console by accessing the value and using the console.log function.

  • Line 3: We pass myArray to the Object.freeze function to prevent it from mutation.

  • Line 4: We access the third element again and assign it a new value.

  • Line 5: We access the third element again and print its value to the console. Suprisingly, it still prints 3, which was its original value.

Conclusion

We can prevent mutation of objects and arrays using the Object.freeze() JavaScript function. We pass the desired object or array as an argument to this function, which later prevents any change to the object’s or array’s data.

This is very important and useful for developers who want to write functions that work and don’t easily crash due to simple internal mutation.