Sub topic 4
Block Scope with let and const
This chapter assumes you can declare variables with var, let, and const, write if statements and for loops, and already know from the previous chapter that var is scoped to the enclosing function. Here you will see how let and const add a smaller unit of scope: the block.
What Counts as a Block
A block is any pair of curly braces that groups statements. Common blocks include:
- The body of an
if,else,while, orfor - The
try,catch, andfinallyparts of an error handler - A bare
{ ... }with no keyword in front of it
Function bodies are blocks too, but they also create a function scope. Names declared with let, const, or class belong to the nearest enclosing block. Names declared with var skip past blocks and attach to the enclosing function, or to the script if there is no function.
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(typeof b); // "undefined" (b is not visible here)The var a declaration escapes the if block. The let b declaration stays inside it.
Loop Variables Stay in the Loop
The header of a for loop belongs to the loop's own scope when you use let. The counter does not leak into the code that follows the loop.
for (let i = 0; i < 2; i++) {
console.log("inside", i);
}
console.log(typeof i); // "undefined"
for (var k = 0; k < 2; k++) {}
console.log(k); // 2With var, the counter k stays around after the loop with its final value. That is a frequent source of bugs, and a later chapter on loop closures shows a sharper version of the same issue.
const Locks the Binding, Not the Value
const has the same block scoping as let, with two extra rules. You must give it a value when you declare it, and you cannot assign a new value to that name later. The object it points to can still change.
const settings = { theme: "dark" };
settings.theme = "light"; // allowed: mutating the object
console.log(settings.theme); // "light"
try {
settings = {}; // not allowed: reassigning the binding
} catch (e) {
console.log(e.name); // "TypeError"
}If you need an object that cannot change, use Object.freeze. const does not do that.
Using Bare Blocks to Limit Lifetime
A bare block lets you keep temporary names out of the surrounding code:
let total;
{
const prices = [3, 4, 5];
const tax = 0.1;
total = prices.reduce((sum, p) => sum + p, 0) * (1 + tax);
}
console.log(total.toFixed(2)); // "13.20"
console.log(typeof prices); // "undefined"Comparison
| Declaration | Scope | Redeclare in same scope | Reassign |
|---|---|---|---|
| `var` | Function or script | Allowed | Allowed |
| `let` | Block | SyntaxError | Allowed |
| `const` | Block | SyntaxError | TypeError |
| `class` | Block | SyntaxError | Allowed, but avoid it |
Common Errors
- Reading a block variable after the block ends. Outside the block the name either refers to an outer variable or throws
ReferenceError: x is not defined. - Redeclaring with let in the same block.
let x = 1; let x = 2;is a SyntaxError, and the whole script fails before any line runs. - Declaring const without a value.
const x;is also a SyntaxError. - Treating const as immutable data. Properties and array elements can still change.
Exercise
What does this code print, and why? function check() { if (true) { var x = "v"; const y = "c"; } return [typeof x, typeof y]; } console.log(check());
Show answer
It prints ["string", "undefined"]. The var x declaration attaches to the function scope of check, so it is still visible after the if block. The const y declaration is confined to the if block, so typeof y outside the block reports "undefined".
Exercise
A teammate writes const list = []; list.push(1); and expects an error. Explain why none occurs, and show how to make the push fail.
Show answer
const only prevents reassigning the name list. It does not stop changes to the array. To block mutation, use const list = Object.freeze([]);. After that, list.push(1) throws a TypeError.