How to Update a Const Array in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 20 20211 min read

banner

Photo by Iswanto Arif

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee