Update A Const Array In JavaScript

A const array in JavaScript cannot be reassigned, but the values of a const array are not immutable, i.e., you can update a const array by accessing an element at a particular index and updating it with a new value. In this post, we will see how to update a const array in JavaScript.

how to update a const array in javascript

How To Update A Const Array In JavaScript

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’];


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 –

  1. Prevents updating existing properties of the object.
  2. Prevents adding new properties to the object.
  3. 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.

So, to answer your question, you cannot update a const array in JavaScript, but you can update the values of a const array if those values are not frozen.

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’];


const newArr = [‘d’, ‘e’, ‘f’];

arr = newArr; // error!

As you can see, this code throws an error because you are trying to reassign a const. So, the only way to update a const array in JavaScript is by updating the values of the elements in the array if they are not frozen.

Leave a Reply