JS Arrays and const

JavaScript Arrays and the const Keyword

A common point of confusion for beginners is how the const keyword behaves when used to declare an array. Does const make the array immutable (unchangeable)?

The short answer is no.


The const Keyword

The const keyword creates a read-only reference to a value. This means:

In other words, you cannot reassign a const array to a new array, but you can freely change its elements.


It is Safe to Mutate a const Array

You can add, remove, or change the elements of an array declared with const without any issues.

Mutating a const Array

// Declare a constant array
const cars = ["Saab", "Volvo", "BMW"];

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

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

console.log(cars); // ["Toyota", "Volvo", "BMW", "Audi"]


Reassignment Will Cause an Error

What you cannot do is reassign the variable to a new array or another value. This will throw a TypeError.

Reassignment Error Example

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

// This will cause an error! cars = ["Toyota", "Volvo", "Audi"]; // TypeError: Assignment to constant variable.

Best Practice: Always declare arrays with const unless you have a specific reason to reassign the entire array. This makes your code safer and more predictable, as it prevents accidental reassignment.


Exercise

?

If you declare an array with `const`, which of the following operations will cause an error?