Sub topic 4
let, const, and Block Scope
This chapter assumes you can write functions, if statements, and for loops. It also assumes you have read the previous chapter on var and function scope. Hoisting, the temporal dead zone, and the loop-closure bug each have their own chapter later. They appear here only where they affect how block scope behaves.
What a block is
A block is any group of statements wrapped in curly braces { ... }. You use them all the time: the body of an if, the body of a for or while loop, the try and catch parts of an error handler, and the braces around a switch statement. You can also write a block on its own, with no keyword in front of it.
let and const are block-scoped. A variable declared with either one exists only from the point it is declared to the closing brace of the nearest enclosing block. Outside that block, the name does not exist. var ignores blocks and attaches to the enclosing function instead.
function checkout(cartTotal) {
if (cartTotal > 100) {
const discount = 0.1;
let finalTotal = cartTotal * (1 - discount);
console.log('Inside block:', finalTotal); // Inside block: 180
}
console.log(typeof discount); // 'undefined'
console.log(typeof finalTotal); // 'undefined'
}
checkout(200);typeof returns 'undefined' here because neither name is in scope after the if block closes. If you wrote console.log(finalTotal) instead, you would get ReferenceError: finalTotal is not defined.
Which constructs create a block scope
Most constructs with braces create a block scope, but some details are easy to miss.
| Construct | Creates a scope for let/const? | Notes |
|---|---|---|
| `if` / `else` body | Yes | Each branch is its own block |
| Bare `{ ... }` block | Yes | Useful for limiting a variable's lifetime |
| `for (let i ...)` loop | Yes | The header variable belongs to the loop, not the outer scope |
| `for...of` / `for...in` | Yes | A fresh binding per iteration, so `const` works |
| `while` / `do...while` body | Yes | The condition cannot declare variables |
| `try` / `catch` / `finally` | Yes | The `catch (err)` parameter is scoped to the catch block |
| `switch` statement | One block for all cases | Cases share a scope unless you add braces |
| Function body | Yes | Also a function scope, which `var` respects |
| Object literal `{ a: 1 }` | No | Braces, but an expression, not a block |
Nested blocks and the scope chain
Blocks can be nested. When code uses a name, the engine looks for it in the current block first. If it is not there, the engine checks the enclosing block, then the next one out, and so on up to the global scope. This sequence of scopes is called the scope chain. Lookup only goes outward. An outer scope can never see names declared in an inner one.
const app = 'shop';
function render() {
const page = 'home';
if (true) {
const widget = 'banner';
{
const label = `${app}/${page}/${widget}`;
console.log(label); // shop/home/banner
}
console.log(typeof label); // 'undefined'
}
}
render();Shadowing
An inner block can declare a variable with the same name as one in an outer scope. The inner declaration shadows the outer one: inside the block, the name refers to the inner variable, and the outer variable is unaffected.
const level = 'outer';
{
const level = 'inner';
console.log(level); // inner
}
console.log(level); // outerShadowing is legal and sometimes useful, but it can be confusing to read. Watch for one trap in particular. Once a block declares a name with let or const, that name refers to the inner variable for the whole block, including the lines above the declaration:
let count = 1;
{
try {
console.log(count); // refers to the inner count, which is not ready yet
} catch (e) {
console.log(e.name); // ReferenceError
}
let count = 2;
}You might expect the first console.log to fall back to the outer count, but it doesn't. The inner count owns the name across its whole block. Until its declaration runs, the inner variable is in the temporal dead zone, which a later chapter covers.
Bare blocks for short-lived variables
A bare block lets you keep temporary variables out of the surrounding scope. That reduces name collisions and makes clear that the values are not needed later.
let report;
{
const rows = [3, 5, 8];
const sum = rows.reduce((a, b) => a + b, 0);
report = `Total: ${sum}`;
}
console.log(report); // Total: 16
console.log(typeof rows); // 'undefined'In practice, extracting a small function often reads better than a bare block. Bare blocks are still useful in long setup code, in tests, and inside switch cases, as shown below.
Loop headers
A let declared in a for loop header belongs to the loop. It does not leak into the surrounding function the way var i does.
for (let i = 0; i < 2; i++) {
const squared = i * i;
console.log(i, squared); // 0 0, then 1 1
}
console.log(typeof i); // 'undefined'
console.log(typeof squared); // 'undefined'The loop body is a block too, so squared is created fresh on every iteration. Declaring it with const is fine because each iteration gets a new binding and nothing reassigns it.
const in loop headers
Whether const works in a loop header depends on the kind of loop:
const items = ['a', 'b', 'c'];
for (const item of items) {
console.log(item); // a, b, c
}
for (const key in { x: 1, y: 2 }) {
console.log(key); // x, y
}
try {
for (const n = 0; n < 3; n++) {
console.log('n =', n); // runs once: n = 0
}
} catch (e) {
console.log(e.name, e.message); // TypeError Assignment to constant variable.
}for...of and for...in create a new binding for each iteration and assign it once, so const is the natural choice there. A classic for loop updates its counter with n++, which is a reassignment. With const, the first pass through the body runs, and then the update step throws a TypeError. Use let for counters.
try and catch
The try, catch, and finally bodies are separate blocks. The catch parameter exists only inside its block.
try {
JSON.parse('{bad json');
} catch (err) {
const reason = err.name;
console.log(reason); // SyntaxError
}
console.log(typeof err); // 'undefined'
console.log(typeof reason); // 'undefined'A common mistake is declaring a result variable inside try and then trying to use it afterward. Declare it before the try with let and assign it inside:
let config;
try {
config = JSON.parse('{"retries": 3}');
} catch (err) {
config = { retries: 0 };
}
console.log(config.retries); // 3switch: one block for every case
The braces of a switch form a single block, and the individual case labels do not create blocks of their own. That causes two problems.
First, declaring the same name in two cases is a redeclaration in one scope, which is a SyntaxError before any code runs:
// This does not parse:
// switch (kind) {
// case 'circle':
// const sides = 0;
// break;
// case 'square':
// const sides = 4; // SyntaxError: Identifier 'sides' has already been declared
// break;
// }Second, a variable declared in one case is visible in later cases. If control jumps straight to a later case, the declaration never ran:
function broken(kind) {
switch (kind) {
case 'a':
let msg = 'from a';
return msg;
case 'b':
msg = 'from b'; // msg is in scope here but was never initialized
return msg;
}
}
try {
broken('b');
} catch (e) {
console.log(e.name); // ReferenceError
}The fix for both problems is to wrap each case body in its own block:
function describe(kind) {
switch (kind) {
case 'circle': {
const sides = 0;
return `circle with ${sides} sides`;
}
case 'square': {
const sides = 4;
return `square with ${sides} sides`;
}
default:
return 'unknown shape';
}
}
console.log(describe('circle')); // circle with 0 sides
console.log(describe('square')); // square with 4 sidesFunction declarations inside blocks
Common errors and how to fix them
The most frequent block-scope bug is declaring a variable inside a branch and then needing it after the branch:
function getStatusBroken(code) {
if (code === 200) {
let status = 'ok';
} else {
let status = 'error';
}
return typeof status; // 'undefined': both status variables are gone
}
function getStatus(code) {
let status;
if (code === 200) {
status = 'ok';
} else {
status = 'error';
}
return status;
}
// Even simpler, with one const and no reassignment:
const getStatusShort = (code) => (code === 200 ? 'ok' : 'error');
console.log(getStatusBroken(200)); // undefined
console.log(getStatus(200)); // ok
console.log(getStatusShort(404)); // errorHere is a quick reference for the problems in this chapter:
| Symptom | Likely cause | Fix |
|---|---|---|
| `ReferenceError: x is not defined` after a block | `x` declared with let/const inside the block | Declare `x` in the outer scope |
| `ReferenceError: Cannot access 'x' before initialization` | Inner declaration shadows an outer `x`, or a switch case was skipped | Rename, move the declaration up, or add case braces |
| `SyntaxError: Identifier 'x' has already been declared` in a switch | Same name declared in two cases | Wrap each case in `{ }` |
| `TypeError: Assignment to constant variable.` in a loop | `const` counter in a classic `for` loop | Use `let` for the counter |
Why block scope is the better default
Block scope keeps each variable close to where it is used. The shorter a variable's lifetime, the fewer lines can accidentally read or overwrite it, and the less a reader has to keep track of. With var, a name declared deep inside an if is visible across the whole function. Block scope also gives each loop iteration its own binding, which fixes a long-standing closure bug covered in a later chapter.
Exercise
Predict the output of this code, line by line. let x = 'global'; function test() { let x = 'function'; if (true) { const x = 'block'; console.log(x); } console.log(x); } test(); console.log(x);
Show answer
It prints 'block', then 'function', then 'global'. Each declaration shadows the outer x only inside its own block or function, and the outer variables are never changed.
Exercise
This function throws "SyntaxError: Identifier 'total' has already been declared". Explain why and rewrite it so it works. function price(type) { switch (type) { case 'basic': const total = 10; return total; case 'pro': const total = 25; return total; } }
Show answer
All cases in a switch share one block, so declaring total twice is a redeclaration in the same scope. Wrap each case body in braces so each const lives in its own block: case 'basic': { const total = 10; return total; } case 'pro': { const total = 25; return total; }. You could also return the literal values directly and drop the variable.
Exercise
Why does for (const item of list) work, while for (const i = 0; i < list.length; i++) throws a TypeError after the first iteration?
Show answer
for...of creates a fresh binding for item on each iteration and assigns it exactly once, so const is never reassigned. The classic for loop keeps updating the counter with i++, which is a reassignment of a const binding and throws "TypeError: Assignment to constant variable." The first iteration's body runs before the update step, which is why the error appears after one pass.