Here is an example:
const arr = [‘a’, ‘b’, ‘c’]; arr[‘0’] = ‘d’; // updates the first element in the array console.log(arr); // [‘d’, ‘b’, ‘c’]
As you can see, we were able to update the first element in the array from ‘a’ to ‘d’ even though arr is a const.
This is because, when you access an element in an array using square bracket notation, you are actually accessing a property of the array object, and properties of objects can be reassigned as we just did.
However, if you try to reassign the entire array like this:
const arr = [‘a’, ‘b’, ‘c’]; arr = [‘e’, ‘f’, ‘g’]; // throws an error
You will get a TypeError because you cannot reassign a const.
If you want an array whose values cannot be changed, you can use the Object.freeze() method like this:
const arr = [‘a’, ‘b’, ‘c’]; Object.freeze(arr); arr[‘0’] = ‘d’; // no error console.log(arr); // [‘a’, ‘b’, ‘c’]
Now, even though we are accessing the first element in the array and trying to reassign it, we are not actually changing the value of the element, because Object.freeze() prevents us from doing so.
Note that you will not get any error when you try to update the values of an array that’s frozen. The values will just not be updated.
Here’s what Object.freeze() does –
- Prevents updating existing properties of the object.
- Prevents adding new properties to the object.
- Prevents removing new properties from the object.
The Object.freeze() method along with the const keyword makes the array immutable, i.e., you cannot reassign or update the array in any way.
If the values are frozen, then you cannot update them. You cannot even assign this array to another array like this –
const arr = [‘a’, ‘b’, ‘c’]; Object.freeze(arr); const newArr = [‘d’, ‘e’, ‘f’]; arr = newArr; // error!