The Variable Declaration - const
const declares a variable that cannot be reassigned. It must be given its value in the declaration, and any later attempt to assign a new value throws an error. Like let, it is block-scoped.
Most variables in a program are set once and never reassigned, so const makes a good default. It tells the reader that the name will refer to the same thing on every line, and it turns an accidental reassignment into an error instead of a silent bug. Use let only for the variables that really do change, such as counters and running totals.
Reassignment throws
Section titled “Reassignment throws”const vatRate = 0.2;
try { vatRate = 0.25;} catch (err) { console.log(`${err.name}: ${err.message}`);}
console.log(vatRate);This prints:
TypeError: Assignment to constant variable.0.2A const also needs a value when it is declared, because it could never be given one later:
const discount;The file fails to load:
SyntaxError: Missing initializer in const declarationThe contents can still change
Section titled “The contents can still change”const protects the variable, not the value it holds. When the value is an object or an array, the variable always points at that same object, but the object itself can still be changed. Properties can be added, changed and deleted, and items can be pushed onto an array:
const basket = { apples: 3 };basket.pears = 2;basket.apples = 5;delete basket.pears;console.log(basket);
const books = ['Emma'];books.push('Middlemarch');console.log(books);This prints:
{ apples: 5 }[ 'Emma', 'Middlemarch' ]To stop an object’s properties changing, freeze it with Object.freeze(). Changes to a frozen object are ignored in sloppy mode and throw a TypeError in strict mode. The freeze is shallow, so an object or array stored inside it can still be changed:
const settings = Object.freeze({ theme: 'dark', fontSize: 16 });settings.fontSize = 20;settings.language = 'en';console.log(settings);
const nested = Object.freeze({ sizes: [12, 14] });nested.sizes.push(16);console.log(nested.sizes);This prints:
{ theme: 'dark', fontSize: 16 }[ 12, 14, 16 ]Seal, Freeze, PreventExtension compares the ways of locking an object.
const in loops
Section titled “const in loops”A for...of or for...in loop creates a new variable for every pass, so const works there. A classic for loop changes one counter with n++, so its counter must be declared with let:
for (const city of ['Leeds', 'York', 'Hull']) { console.log(city);}
try { for (const n = 0; n < 3; n++) { console.log(n); }} catch (err) { console.log(`${err.name}: ${err.message}`);}This prints:
LeedsYorkHull0TypeError: Assignment to constant variable.The first pass of the classic loop runs, and the error comes when n++ tries to reassign the counter.
Steve Griffith covers this topic in his video Why Should I Use const in JavaScript.