HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Array Const

In modern JavaScript (ES6+), it has become the standard practice to declare arrays using the const keyword. This does not mean the array is unchangeable, but rather that the identifier (the name) cannot be reassigned to a different value.


Constant Reference, Not Constant Value

The const keyword defines a constant reference to an array. Because of this, we can still change the elements of a constant array.

What You CAN Do:

  • You can change the value of an existing element.
  • You can add new elements to the array.
  • You can remove elements from the array.
const cars = ["Saab", "Volvo", "BMW"];

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

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

The Restriction

What You CANNOT Do:

You cannot reassign a const array. If you try to give the array variable a completely new value, JavaScript will throw an error.

const cars = ["Saab", "Volvo", "BMW"];

cars = ["Toyota", "Audi"]; // ERROR: Assignment to constant variable.

Block Scope

An array declared with const has block scope. This means an array declared inside a block {} is not accessible from outside the block.

const cars = ["Saab", "Volvo"];
{
  const cars = ["Toyota", "BMW"]; // This is a different array!
}
console.log(cars[0]); // Result: "Saab"

Why Use const?

  • Safety: It prevents accidental reassignment of your important data collections
  • Clarity: It tells other developers that this variable will always point to the same array
  • Best Practice: Most modern JavaScript style guides (like Airbnb or Google) require using const for arrays

Key Points to Remember

  • const is the standard for declaring arrays in ES6+
  • Elements can be changed, added, or removed (Mutability)
  • The variable name cannot be reassigned to a new value
  • const arrays are block-scoped
  • Redeclaring a const array in the same scope is not allowed