Introduced in 2015, JavaScript brought a significant keyword: const. It’s now a common practice to declare arrays using const.
Example
const cars = [“Saab”, “Volvo”, “BMW”]; |
Once declared with const, an array cannot be reassigned.
Example
const cars = [“Saab”, “Volvo”, “BMW”]; cars = [“Toyota”, “Volvo”, “Audi”]; // ERROR |
The keyword const might be a bit misleading.
It doesn’t create a constant array; rather, it establishes a constant reference to an array.
Consequently, although you can’t reassign the array itself, you can still modify its elements.
You can modify the elements of a constant array.
Example
// You can create a constant array: const cars = [“Saab”, “Volvo”, “BMW”]; // You can change an element: cars[0] = “Toyota”; // You can add an element: cars.push(“Audi”); |