Sub topic 4
Block Scope with let and const
This chapter assumes you can write functions, if statements, and for loops, and that you know function scope: a var declared anywhere inside a function belongs to that whole function. Here we add a smaller unit of scope. A block is any region of code wrapped in curly braces { }. With let and const, that region gets its own set of variables.
Before ES2015, JavaScript had only global scope and function scope. Developers who wanted a short-lived variable had to wrap code in an extra function to get one. let, const, and class declarations made the block a real scope boundary. Nearly every variable in modern JavaScript is block-scoped.
What Counts as a Block
A block is a statement wrapped in braces. You see blocks in these places:
- The body of
if,else,while,do...while, andfor - The
try,catch, andfinallyclauses - The body of a
switchstatement (one block for all its cases) - A standalone pair of braces that is not attached to any keyword
Object literals also use braces, but they are not blocks. const point = { x: 1 } creates an object and no scope.
Function bodies are blocks as well, and they also create function scope. A var inside a plain block escapes to the nearest function. A let or const stays inside the nearest block.
let and const Stay Inside Their Block
The core rule fits in one example:
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(typeof b); // "undefined" (b is not visible here)var a is attached to the enclosing function or script, so it is still visible after the if ends. let b exists only between the braces. Outside them, the name b is unknown. typeof reports "undefined" for unknown names instead of throwing. A plain console.log(b) would throw a ReferenceError.
Block scoping also controls lifetime. When execution leaves a block, nothing can reach the block's bindings anymore, unless a closure captured them (a later chapter covers closures). The engine can then reclaim the memory. Keeping a large temporary array in a block shows the reader, and the engine, that it is not needed afterwards.
Standalone Blocks
You can add braces anywhere a statement is allowed. The only purpose is to limit scope:
let total = 0;
{
const prices = [4, 8, 15];
const tax = 0.2;
for (const p of prices) {
total += p * (1 + tax);
}
}
console.log(total.toFixed(2)); // "32.40"
console.log(typeof prices); // "undefined"prices and tax exist only inside the braces, so they cannot collide with any other prices later in the file. A standalone block is a lightweight replacement for the old immediately invoked function expression (IIFE) pattern, (function () { ... })().
const Locks the Binding, Not the Value
const follows the same scoping rules as let, plus two more:
- You must give it a value in the declaration.
const x;is aSyntaxError. - You cannot assign to it again. Trying throws a
TypeErrorat runtime.
A common error is to treat const as "immutable". It isn't. const stops the name from pointing somewhere else. It does nothing to the object the name points to.
const config = { debug: false };
config.debug = true; // allowed: mutating the object
console.log(config.debug); // true
try {
config = { debug: false }; // not allowed: rebinding the name
} catch (e) {
console.log(e.name); // "TypeError"
}
const frozen = Object.freeze({ debug: false });
frozen.debug = true; // ignored in sloppy mode, TypeError in strict mode
console.log(frozen.debug); // falseFor a value that really cannot change, combine const with Object.freeze. Remember that freeze is shallow: nested objects stay mutable.
Loop Headers Create Their Own Scope
A let or const declared in a for header belongs to the loop. It is not visible after the loop ends:
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); // 2 (var leaked out of the loop)const works in for...of and for...in headers because each iteration gets a new binding: for (const item of list). It fails in a classic counting loop. for (const n = 0; n < 3; n++) throws a TypeError on the first n++.
The fact that let creates a new binding per iteration is the fix for a famous closure bug. The chapter "The Classic Loop Closure Bug" covers it in detail.
Redeclaration Is an Error
Inside a single scope, var lets you declare the same name twice without complaint. let, const, and class do not:
var count = 1;
var count = 2; // fine with var
console.log(count); // 2
try {
new Function("let total = 1; let total = 2;");
} catch (e) {
console.log(e.name); // "SyntaxError"
}This error happens at parse time. The engine rejects the whole script before running any of it. That is why the example wraps the bad code in new Function: the error stays contained, and the rest of the file still runs. The same rule applies if you mix keywords, as in var x and let x in the same scope.
Declaring the same name in a nested block is legal. That is shadowing, which has its own chapter.
The switch Gotcha
All the case clauses of a switch statement share one block. If two cases declare the same name with let or const, you get the redeclaration error above:
try {
new Function(`
switch (1) {
case 1: let msg = "one"; break;
case 2: let msg = "two"; break;
}
`);
} catch (e) {
console.log(e.name); // "SyntaxError"
}
function describe(n) {
switch (n) {
case 1: {
const msg = "one";
return msg;
}
case 2: {
const msg = "two";
return msg;
}
default:
return "other";
}
}
console.log(describe(2)); // "two"The fix is to wrap each case body in its own braces. Each case then gets a private block.
There is a second, quieter trap. If case 1 declares a let and case 2 reads it, a jump straight to case 2 reads a binding that was never initialized. That throws a ReferenceError. The chapter on the temporal dead zone explains why.
Other Block-Scoped Declarations
let and const are not the only declarations that follow block rules:
| Declaration | Scope | Can redeclare in same scope | Must initialize | Can reassign |
|---|---|---|---|---|
| `var` | Function or script | Yes | No | Yes |
| `let` | Block | No | No | Yes |
| `const` | Block | No | Yes | No |
| `class` | Block | No | Yes (the class body) | Yes, but avoid it |
| `catch (err)` parameter | The catch block | No (with `let`/`const`) | Set by the throw | Yes |
| `function` in a block | Block (strict mode) | Varies | Yes (the body) | Yes |
The catch parameter is visible only inside its catch clause. You can reuse the name err in every try statement without a conflict.
Function Declarations Inside Blocks
Function declarations inside blocks behave differently depending on the mode. In strict mode, which includes every ES module and every class body, they are block-scoped:
"use strict";
{
function helper() {
return "inside";
}
console.log(helper()); // "inside"
}
console.log(typeof helper); // "undefined"Remove "use strict" and run the same file as a classic script, and the last line prints "function". The specification keeps an old browser-compatibility rule for sloppy mode. Under that rule, a function declared in a block also creates a var-like binding in the enclosing function. That binding stays undefined until the block runs. Code that depends on this behavior is fragile.
Common Errors
- Reading a variable after its block ends. You declare
let resultinside anifand then use it below theif. Fix it by declaringlet result;before the block and assigning it inside. - Expecting
constto freeze objects. Mutations still work. UseObject.freeze, or copy the object instead of changing it. - Duplicate
letacrossswitchcases. Wrap each case in braces. - Using
constin a countingforloop. Useletfor the counter. Keepconstforfor...ofandfor...in. - Mixing
varinto block-scoped code. Onevarinside a block escapes to the whole function and can clash with names you expected to stay separate.
Exercise
Predict the three lines this code logs, and explain each one. function run() { if (true) { var x = "var"; let y = "let"; const z = { v: 1 }; z.v = 2; console.log(z.v); } console.log(x); console.log(typeof y); } run();
Show answer
It logs 2, then "var", then "undefined". z.v = 2 is allowed because const prevents rebinding z, not changing the object. x was declared with var, so it belongs to run's function scope and is still visible after the if block. y was declared with let, so it exists only inside the if block. Outside the block the name is unknown, and typeof reports "undefined" instead of throwing.
Exercise
This function throws a SyntaxError before it ever runs. Find the cause and rewrite it so that label(1) returns "small" and label(5) returns "large". function label(n) { switch (true) { case n < 3: let text = "small"; return text; default: let text = "large"; return text; } }
Show answer
All cases of a switch share one block, so the two let text declarations redeclare the same name in the same scope, which is a parse-time SyntaxError. Give each clause its own block: case n < 3: { const text = "small"; return text; } default: { const text = "large"; return text; }. Each text now lives in a separate block, so the names no longer collide.
Exercise
A teammate writes for (const i = 0; i < 3; i++) { console.log(i); }. What happens, and why does for (const item of [1, 2, 3]) work when this does not?
Show answer
The loop logs 0 and then throws a TypeError when i++ tries to assign to the const binding. A classic for loop carries the counter forward by updating it, which const forbids. A for...of loop creates a fresh binding for each iteration and never reassigns it, so const is valid there.