In 2015, JavaScript introduced the const
keyword, which has since become a standard way to declare variables that should not be reassigned. This is especially useful when working with arrays.
const cars = ["Toyota", "Honda", "Ford"];
console.log(cars); // Output: ["Toyota", "Honda", "Ford"]
Cannot Reassign Arrays Declared with const
An array declared with const
cannot be reassigned to a new array:
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR: Cannot reassign a const variable
This will result in a TypeError because const
prevents reassigning the reference to a new array.
The const
keyword does not make the array immutable; it only makes the reference constant. This means you can still modify the array's contents:
Elements Can Be Modified
You can update values and add new elements to a const
array:
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Toyota"; // Modifies existing element
cars.push("Audi"); // Adds a new element
console.log(cars); // Output: ["Toyota", "Volvo", "BMW", "Audi"]
Array Must be Initialized
When declaring a const
array, it must be initialized immediately:
const cars = ["Saab", "Volvo", "BMW"];
console.log(cars); // Output: ["Saab", "Volvo", "BMW"]
Declaring a const
array without initializing it will cause an error:
const cars;
cars = ["Saab", "Volvo", "BMW"]; // ERROR: Missing initializer in const declaration
Scope of const
Arrays
A const
array has block scope, meaning it is only accessible within the block where it is defined.
const cars = ["Toyota", "Volvo", "BMW"];
console.log(cars[0]); // Output: "Toyota"
{
const cars = ["Honda", "Volvo", "BMW"];
console.log(cars[0]); // Output: "Honda"
}
console.log(cars[0]); // Output: "Toyota"
Redeclaring Arrays
Redeclaring an array using var
is allowed:
var cars = ["Honda", "BMW"];
var cars = ["Toyota", "Ford"];
cars = ["Mazda", "Audi"];
console.log(cars); // Output: ["Mazda", "Audi"]
However, redeclaring or reassigning an array declared with const
in the same scope is not allowed:
const cars = ["Toyota", "BMW"];
const cars = ["Toyota", "BMW"]; // ERROR: Identifier 'cars' has already been declared
Redeclaring in Different Blocks
Redeclaring an array with const
in different blocks is permitted:
const cars = ["Volvo", "BMW"];
console.log(cars); // Output: ["Volvo", "BMW"]
{
const cars = ["Toyota", "BMW"];
console.log(cars); // Output: ["Toyota", "BMW"]
}
{
const cars = ["Audi", "BMW"];
console.log(cars); // Output: ["Audi", "BMW"]
}