const: Declaring Immutable BindingsThe 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.
An initializer for a constant is required; you must specify its value in the same declaration.
// const FOO; // SyntaxError: Missing initializer in const declarationconst PI = 3.14159;
if (PI > 3) { console.log("Pi is greater than 3!"); }
Once declared, the variable cannot be reassigned.
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 ImmutabilityA 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 ObjectsYou cannot reassign the object itself, but you can change its properties.
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 ArraysSimilarly, you can modify the contents of an array (e.g., by pushing new items) but you cannot reassign the array variable.
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
Like let, const declarations are block-scoped. A constant declared within a block {} is only accessible within that block.
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
Which of the following is TRUE about variables declared with const?