Skip to content

Block bindings: block scope and the TDZ (ES2015)

  • Which declarations are block-scoped and what counts as a block.
  • How the temporal dead zone (TDZ) works, including why typeof can throw.
  • How for (let ...) creates a fresh binding per iteration, and what that means for closures.
  • The traps: shared switch scope, block-level functions in sloppy mode, and top-level let in classic scripts.
  • When to choose const, let or var, and why const does not make objects immutable.

This page covers the scoping rules first, then choosing between let, const and var, including const and object mutation.

TL;DR: since ECMAScript 2015, let, const and class declarations (and, in strict code, function declarations) belong to the nearest enclosing block, not the whole function. The binding exists from the start of the block but cannot be used until its declaration runs; that gap is the temporal dead zone. Loops with let in the head get a new binding for every iteration.

Before ES2015, JavaScript had only function scope. A var inside an if or loop belonged to the whole function, so closures created in a loop shared one variable, and the workaround was an IIFE to create a new scope.

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs), unless the sample says otherwise. ES modules are always strict mode. The output shown under each sample was produced with Node.js 22.23.

// Before: var is function-scoped, so every callback shares one `i`.
const varCallbacks = [];
for (var i = 0; i < 3; i++) {
varCallbacks.push(() => `retry ${i}`);
}
console.log(varCallbacks.map((f) => f()));
// The ES5 workaround: an IIFE creates a new function scope per iteration.
const iifeCallbacks = [];
for (var j = 0; j < 3; j++) {
(function (attempt) {
iifeCallbacks.push(() => `retry ${attempt}`);
})(j);
}
console.log(iifeCallbacks.map((f) => f()));
// ES2015: a let in the loop head gets a fresh binding per iteration.
const letCallbacks = [];
for (let k = 0; k < 3; k++) {
letCallbacks.push(() => `retry ${k}`);
}
console.log(letCallbacks.map((f) => f()));

Output:

[ 'retry 3', 'retry 3', 'retry 3' ]
[ 'retry 0', 'retry 1', 'retry 2' ]
[ 'retry 0', 'retry 1', 'retry 2' ]

A block is any { ... } statement list: a bare block, the body of if, loops, try, catch and finally, and the body of a switch (one block for all its cases). Loop heads such as for (let i ...) get their own scope too.

When execution enters a block, the engine creates all of its bindings at once, uninitialized; each becomes usable only when its declaration is evaluated. Any access before that throws a ReferenceError: the temporal dead zone. It is “temporal” because what matters is when code runs: a function written above a const may read it if called after the declaration.

const tryIt = (label, fn) => {
try { console.log(label, '->', fn()); }
catch (e) { console.log(label, '->', `${e.constructor.name}: ${e.message}`); }
};
// 1. Any pair of braces is a block.
{
const discount = 0.1;
console.log('inside block', discount);
}
tryIt('outside block', () => discount);
// 2. Temporal dead zone: the binding exists from the start of the block,
// but reading it before the declaration runs throws. Even typeof throws.
tryIt('typeof in TDZ', () => { const t = typeof total; let total = 5; return t; });
tryIt('typeof undeclared', () => typeof neverDeclared);
tryIt('shadow with itself', () => { const total = 1; { let total = total + 1; return total; } });
// 3. Functions declared earlier can reference later bindings, as long as
// they run after the declaration.
function readRate() { return taxRate; }
tryIt('call before init', readRate);
const taxRate = 0.2;
tryIt('call after init', readRate);
// 4. Per-iteration copies: each iteration starts with the previous value.
const seen = [];
for (let n = 0; n < 6; n++) {
if (n === 1) n += 2; // the change carries into the next iteration
seen.push(() => n);
}
console.log('per-iteration', seen.map((f) => f()));
// 5. const works in for...of and for...in (fresh binding each time) but not in a counting loop.
for (const id of ['ord-1', 'ord-2']) console.log('for...of const', id);
tryIt('const counter', () => { for (const c = 0; c < 2; c++) {} });
// 6. class declarations are block-scoped and have a TDZ too.
tryIt('class in TDZ', () => { const r = new Receipt(); class Receipt {} return r; });
{
class Receipt {}
}
tryIt('class outside block', () => Receipt);

Output:

inside block 0.1
outside block -> ReferenceError: discount is not defined
typeof in TDZ -> ReferenceError: Cannot access 'total' before initialization
typeof undeclared -> undefined
shadow with itself -> ReferenceError: Cannot access 'total' before initialization
call before init -> ReferenceError: Cannot access 'taxRate' before initialization
call after init -> 0.2
per-iteration [ 0, 3, 4, 5 ]
for...of const ord-1
for...of const ord-2
const counter -> TypeError: Assignment to constant variable.
class in TDZ -> ReferenceError: Cannot access 'Receipt' before initialization
class outside block -> ReferenceError: Receipt is not defined

Three details from that output:

  • typeof is only safe for names that are not declared at all. For a binding in its TDZ it throws.
  • let total = total + 1 in an inner block reads the inner total, which is still in its TDZ. The outer binding is already shadowed.
  • In a for (let ...) loop the spec copies the current value into a new binding before each iteration (CreatePerIterationEnvironment). Closures capture that iteration’s binding, and changes in the body carry over. The increment then assigns to the binding, which is why for (const c = 0; ...; c++) fails.
// The whole switch body is ONE block: case clauses share it.
const check = (label, source) => {
try { new Function(source); console.log(`ok ${label}`); }
catch (e) { console.log(`SyntaxError ${label}: ${e.message}`); }
};
check('same name in two cases', `
switch (status) {
case 'paid': const message = 'Thanks'; break;
case 'failed': const message = 'Retry'; break;
}`);
check('braces per case', `
switch (status) {
case 'paid': { const message = 'Thanks'; break; }
case 'failed': { const message = 'Retry'; break; }
}`);
check('let redeclares a var', 'var total = 1; let total = 2;');
function describe(status) {
switch (status) {
case 'paid':
let note = 'Payment received';
return note;
case 'refunded':
note = 'Refund issued'; // same binding, but its declaration never ran
return note;
}
}
console.log(describe('paid'));
try { describe('refunded'); } catch (e) { console.log(`${e.constructor.name}: ${e.message}`); }

Output:

SyntaxError same name in two cases: Identifier 'message' has already been declared
ok braces per case
SyntaxError let redeclares a var: Identifier 'total' has already been declared
Payment received
ReferenceError: Cannot access 'note' before initialization

Redeclaring a name with let, const or class in the same scope is an early SyntaxError: the whole script or module fails to load.

In strict code (modules, classes, 'use strict'), a function declared in a block is scoped to that block. In sloppy mode, the spec’s Annex B keeps the legacy browser behavior: the function also gets a function-level var binding once the block runs. Save this sample as blocks.cjs (CommonJS files are sloppy by default) and run node blocks.cjs:

// Block-level function declarations: the legacy web semantics (Annex B)
// also create a function-scoped var binding in sloppy mode.
function sloppy() {
const before = typeof applyCoupon;
{
function applyCoupon() { return 'coupon applied'; }
}
return [before, typeof applyCoupon];
}
function strict() {
'use strict';
{
function applyCoupon() { return 'coupon applied'; }
}
return typeof applyCoupon;
}
console.log('sloppy:', sloppy());
console.log('strict:', strict());

Output:

sloppy: [ 'undefined', 'function' ]
strict: undefined

At the top level of a classic script (no type="module"), var and function declarations become properties of the global object, but let, const and class go into a global lexical scope shared by all scripts. They are visible to later scripts but are not properties of globalThis, and redeclaring one in another script fails. Node’s vm module simulates two scripts sharing one global:

import vm from 'node:vm';
// Two classic scripts sharing one global, like two <script> tags in a page.
const context = vm.createContext({ console });
vm.runInContext(`
var legacyFlag = true;
let apiBase = 'https://api.example.test';
`, context);
vm.runInContext(`
console.log('var on global object:', 'legacyFlag' in globalThis);
console.log('let on global object:', 'apiBase' in globalThis);
console.log('let visible to later scripts:', apiBase);
`, context);
try {
vm.runInContext(`let apiBase = 'https://staging.example.test';`, context);
} catch (e) {
console.log(`${e.constructor.name}: ${e.message}`);
}

Output:

var on global object: true
let on global object: false
let visible to later scripts: https://api.example.test
SyntaxError: Identifier 'apiBase' has already been declared

In ES modules none of this applies: every top-level declaration, var included, is scoped to the module.

let and const were introduced together in ECMAScript 2015 and share the block-scoping rules above. They differ in one thing: a const binding must be initialized in its declaration and can never be reassigned, while a let binding can. var is the pre-2015 keyword with function scope, hoisting to undefined, redeclaration allowed, and, in classic scripts, a property on the global object.

The common guidance, and the default of linters such as ESLint’s prefer-const rule, is: use const for every binding that is not reassigned, let for the ones that are (counters, accumulators, values set in branches), and var only in legacy code. const tells the reader “this name always refers to the same value”, which makes code easier to follow.

const is about the binding, not the value. A const object or array can still be mutated: you can push to it and change its properties. To make an object itself read-only, use Object.freeze, which is shallow: nested objects stay mutable unless you freeze them too. In strict mode, writing to a frozen object throws a TypeError; in sloppy mode the write is silently ignored.

const order = { id: "ord-1", lines: [{ sku: "MUG-01", qty: 1 }] };
order.lines.push({ sku: "TEE-03", qty: 2 }); // mutation is allowed
order.status = "paid";
console.log(order.lines.length, order.status);
try {
order = { id: "ord-2" }; // reassignment is not
} catch (error) {
console.log(error.name + ":", error.message);
}
let total = 0; // reassigned, so let
for (const line of order.lines) total += line.qty;
console.log("units:", total);
const frozen = Object.freeze({ id: "ord-1", customer: { tier: "basic" } });
try {
frozen.id = "changed";
} catch (error) {
console.log(error.name + ":", error.message);
}
frozen.customer.tier = "gold"; // freeze is shallow
console.log(frozen.id, frozen.customer.tier);
try {
new Function("const missing;");
} catch (error) {
console.log(error.name + ":", error.message);
}

Output:

2 paid
TypeError: Assignment to constant variable.
units: 3
TypeError: Cannot assign to read only property 'id' of object '#<Object>'
ord-1 gold
SyntaxError: Missing initializer in const declaration

Pitfalls:

  • Thinking const makes data immutable. It only prevents reassignment. Freeze the object, or better, avoid mutating shared data.
  • Using let “just in case”. An unnecessary let tells readers the value may change and hides real reassignments. Start with const and switch when needed.
  • Mixing var into modern code. One var reintroduces function scope and early undefined reads in the middle of block-scoped code.

OrdersPortal schedules one notification per order. The loop relies on a fresh index per iteration, the body’s const bindings are new each time, and each case has its own braces. The timers fire in reverse order to prove each closure kept its own values.

// notify.mjs - OrdersPortal: schedule one notification per order.
const orders = [
{ id: 'ord-1', status: 'paid', total: 40 },
{ id: 'ord-2', status: 'refunded', total: 15 },
{ id: 'ord-3', status: 'shipped', total: 99 },
];
function buildMessage(order) {
switch (order.status) {
case 'paid': {
const subject = `Order ${order.id} confirmed`;
return { subject, body: `We received ${order.total} USD.` };
}
case 'refunded': {
const subject = `Refund for ${order.id}`; // same name, separate block
return { subject, body: `${order.total} USD is on its way back.` };
}
default: {
const subject = `Update on ${order.id}`;
return { subject, body: `Status: ${order.status}.` };
}
}
}
const sent = [];
for (let index = 0; index < orders.length; index++) {
const order = orders[index]; // the loop body is a block: new binding each iteration
const message = buildMessage(order);
// Each timer closes over this iteration's `index`, `order` and `message`.
setTimeout(() => {
sent.push(`${index + 1}/${orders.length} ${order.id}: ${message.subject}`);
}, (orders.length - index) * 10); // fire in reverse order to prove the capture
}
setTimeout(() => console.log(sent.join('\n')), 50);

Output:

3/3 ord-3: Update on ord-3
2/3 ord-2: Refund for ord-2
1/3 ord-1: Order ord-1 confirmed
  • Using typeof as a TDZ guard. typeof x throws while x is in its TDZ. Move the declaration up instead.
  • Declarations directly under case. All cases share one scope, so the same name twice is a SyntaxError, and a binding declared in one case is in its TDZ in the others. Wrap each case body in braces.
  • Circular module imports. An imported const or class that the other module has not initialized yet throws Cannot access ... before initialization. Break the cycle or defer the access into a function.
  • Expecting let at the top of a script to create window.x. It does not; use globalThis.x = ... explicitly if you truly need a global property.

Block scoping is the default for new code: declare each variable in the smallest block that needs it, use a bare block { ... } for short-lived temporaries, and brace every case that declares something. Keep var only for code that relies on function scope or on global object properties in classic scripts; see Choosing let const or var for the keyword trade-offs.

According to MDN’s browser compatibility data, let with full ES2015 semantics is supported in Chrome 49, Edge 14, Firefox 44, Safari 10 and Node.js 6.0.0; Deno 1.0 and Bun 1.0 support it. Internet Explorer 11 and Edge 12–13 supported let only partially: a let in a for loop head did not create a separate binding per iteration. Block-level function declarations are supported in Chrome 49, Edge 12, Firefox 46, Safari 10 and Node.js 4.0.0. Compilers that target ES5 emulate block scope by renaming shadowed variables and wrapping loop bodies that create closures in functions. Babel’s block-scoping transform does not emulate the TDZ unless its tdz option is enabled (it defaults to false), so compiled code may read undefined where native code throws.

1. What is the temporal dead zone? The period between entering a scope, when a let, const or class binding is created, and the evaluation of its declaration. Any access in that period throws a ReferenceError, even typeof.

2. Why does for (let i = 0; i < 3; i++) setTimeout(() => console.log(i)) print 0, 1, 2 while the var version prints 3, 3, 3? With var there is one function-scoped i that all callbacks share, and it is 3 when they run. With let in the loop head, each iteration gets a new binding initialized from the previous one, so each callback captures its own value.

3. Why does declaring const message in two case clauses fail? The whole switch body is one block, so both declarations are in the same scope, which is an early SyntaxError. Braces around each case body create separate blocks.

4. Senior scenario: a legacy page loads several classic scripts that share state through top-level var. A refactor changes them to let and a third-party widget breaks. Why, and how do you migrate? Top-level var creates global object properties; top-level let does not, so lookups such as window.config return undefined, and duplicate names across scripts become load-time SyntaxErrors. Make the shared contract explicit (globalThis.OrdersPortalConfig = ... in one place, or better, ES module imports), then convert the remaining vars.

  • let, const, class and (in strict code) function declarations are scoped to the nearest block.
  • Bindings exist from the start of the block but are unusable until declared: the TDZ.
  • for (let ...) copies the binding per iteration; for...of and for...in create a fresh one each time.
  • A switch body is a single block; give each case its own braces.
  • Top-level let and const in classic scripts are global but not properties of globalThis.