Array with Const
Before we start learning about const with arrays, let's first review what const is and how it works.
Basically the const keyword is used to declare a variable that cannot be reassigned to a new value.
However, when declaring an array with const, the values within the array can still be changed or modified.
For example:
const myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // [1, 2, 3, 4]
In this example:
- We declare a constant
myArrayand assign it an initial value of[1, 2, 3]. - We then use the
push()method to add the value4to the end of the array. - Despite being declared with
const,myArraycan still be modified by adding new elements to it.
Here if we try to reassign the entire array to a new value, we will get an error:
const myArray = [1, 2, 3];
myArray = [4, 5, 6]; // TypeError: Assignment to constant variable.
In this example:
We are attempting to reassign
myArrayto a new value of[4, 5, 6].Since
myArraywas declared withconst, this will result in a TypeError.
info
When using const with arrays in JavaScript, note that the variable cannot be reassigned to a new value.