Skip to content

Const Arrays

It is a common practice to declare arrays with the const keyword.

1. Cannot be Reassigned

An array declared with const cannot be reassigned:

const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"];    // ERROR

2. Elements CAN be Changed

It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array:

// You can change an element:
cars[0] = "Toyota";

// You can add an element:
cars.push("Audi");

3. Block Scope

An array declared with const has Block Scope.

const cars = ["Saab", "Volvo", "BMW"];
{
  const cars = ["Toyota", "Volvo", "BMW"]; 
  // Here cars[0] is "Toyota"
}
// Here cars[0] is "Saab"

Always use Const

Unless you intend to reassign the entire array variable to a completely new array, always use const for arrays and objects.