How to Update a Const Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 20, 2021

banner

Photo from Unsplash

Update a Const Array in JavaScript #

Use bracket notation to update the values of an array that was declared using the const keyword, e.g. arr[0] = 'new value'. The elements of an array declared using const can be updated directly, but the variable cannot be reassigned.

index.js
const arr = ['hello', 'world']; // ✅ works arr[0] = 'test'; console.log(arr); // ['test', 'world'] // ⛔️ doesn't work // 👇️ Error: Assignment to constant variable. arr = ['test', 'world'];

When a variable is declared using the const keyword, the variable cannot be reassigned, however if the variable is an array or an object, its values can directly be updated.

index.js
// ✅ works const arr = ['one'] arr[0] = 'two' console.log(arr); // 👉️ ['two'] const test = 'one' // ⛔️️ Error: Assignment to constant variable. test = 'two';

If you need to create an array whose values cannot be changed, you can use the Object.freeze method.

index.js
const arr = ['apple', 'banana']; Object.freeze(arr); arr[0] = 'pear'; console.log(arr); // 👉️ {country: 'Chile'}

The Object.freeze method is used to freeze an array or an object.

After an array is frozen:

  • its elements cannot be changed
  • new elements cannot be added to the array
  • existing elements cannot be removed from the array
The combination of using the const keyword and the Object.freeze method, makes the array immutable.

In closing, declaring a variable using the const keyword means that the variable cannot be reassigned, it doesn't make the value stored in the variable immutable.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.