JS Const

JavaScript const: Declaring Immutable Bindings

The const declaration creates a block-scoped, read-only reference to a value. This means that once a variable is declared with const, its identifier cannot be reassigned.

Many style guides (including MDN's) recommend using const over let whenever a variable is not reassigned in its scope. This makes the intent clear that a variable's identifier will not change.

Basic Syntax & Rules

An initializer for a constant is required; you must specify its value in the same declaration.

`const` requires an initializer

// const FOO; // SyntaxError: Missing initializer in const declaration

const PI = 3.14159;

if (PI > 3) { console.log("Pi is greater than 3!"); }

Once declared, the variable cannot be reassigned.

Reassignment Error

const number = 42;

try { number = 99; } catch (err) { console.log(err); // Expected output: TypeError: Assignment to constant variable. }

console.log(number); // Expected output: 42


const and Immutability

A common misconception is that const makes values immutable. However, const only ensures that the variable binding is constant, not the value it holds. If the value is an object or an array, its contents (e.g., properties or items) can be altered.

const with Objects

You cannot reassign the object itself, but you can change its properties.

Mutating a `const` Object

const MY_OBJECT = { key: "value" };

// This is allowed: Mutating the object's property MY_OBJECT.key = "otherValue"; console.log(MY_OBJECT.key); // "otherValue"

// This will fail: Attempting to reassign the constant variable // MY_OBJECT = { OTHER_KEY: "value" }; // TypeError

To make an object's values truly immutable, you would need to use a method like Object.freeze().

const with Arrays

Similarly, you can modify the contents of an array (e.g., by pushing new items) but you cannot reassign the array variable.

Mutating a `const` Array

const MY_ARRAY = [];

// This is allowed: Pushing a new item into the array MY_ARRAY.push("A"); console.log(MY_ARRAY); // ["A"]

// This will fail: Attempting to reassign the constant variable // MY_ARRAY = ["B"]; // TypeError


Block Scoping

Like let, const declarations are block-scoped. A constant declared within a block {} is only accessible within that block.

Block Scope Example

const MY_FAV = 7;

if (MY_FAV === 7) { // This is fine, it's a new variable in a new block scope const MY_FAV = 20; console.log("Inside block:", MY_FAV); // 20 }

console.log("Outside block:", MY_FAV); // 7


Exercise

?

Which of the following is TRUE about variables declared with const?