Borislav Hadzhiev
Sat Nov 20 2021·1 min read
Photo by Iswanto Arif
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.
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.
// ✅ 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.
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:
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.