Scope in JavaScript: Block, Function, Module and Global Scope and the Temporal Dead Zone
Where a variable is visible and why: lexical scope and the scope chain, block, function, module and global scope, shadowing, switch-case and loop scopes, the temporal dead zone explained with every case that throws, and how scope sets up closures.
kvi5hnuCode Sprout team member7 min readOn this page
The scope of a variable is the region of code where its name can be used. Scope answers questions such as: why can't I use this variable here? Why did my function see the "wrong" value? Why does accessing a let variable one line too early throw? This article covers the four kinds of scope, the lookup rules that connect them, and the temporal dead zone, the rule behind those early-access errors.
The kinds of scope
| Scope | Created by | Holds |
|---|---|---|
| Global | the environment, once | built-ins, host APIs, and top-level declarations of classic scripts |
| Module | each ES module file (and each Node.js CommonJS file) | that file's top-level declarations |
| Function | each call of a function | parameters, vars, and declarations at the top of the body |
| Block | any { ... }: if, for, while, switch, try, catch or a bare block | let, const and class declarations (and, in strict code, function declarations) |
var ignores blocks and attaches to the nearest function, module or global scope (article 26). Everything else respects blocks:
{
const insideBlock = "only here";
console.log(insideBlock);
}
console.log(typeof insideBlock); // not visible outside the braces
if (true) {
let fromIf = 1;
}
console.log(typeof fromIf);
try {
throw new Error("x");
} catch (err) { // err is scoped to the catch block
console.log(err.message);
}
console.log(typeof err);
only here
undefined
undefined
x
undefined
A bare block { ... } is a handy way to keep temporary variables from leaking into the rest of a long function.
Lexical scope and the scope chain
Scopes nest, and an inner scope can see the variables of every scope around it. When you use a name, the engine looks in the current scope, then the enclosing one, and so on outward until it reaches the global scope. If the name isn't found anywhere, reading it throws a ReferenceError.

Crucially, the nesting is determined by where code is written in the source, not by where a function is called from. This is called lexical (or static) scope:
const source = "module";
function report() {
return source; // looks outward from where report is written
}
function caller() {
const source = "caller"; // invisible to report
return report();
}
console.log(caller());
module
Even though report is called from inside caller, it can't see caller's variables. Some older languages used dynamic scope, where the call stack decides; JavaScript never does (this is the one thing that depends on how a function is called, part 8).
Lexical scope is what makes closures possible: a function remembers the scope it was created in, even after that scope's function has returned.
function makeGreeter(greeting) {
return name => `${greeting}, ${name}!`; // remembers greeting
}
const hello = makeGreeter("Hello");
const hola = makeGreeter("Hola");
console.log(hello("Ana"), hola("Bea"));
Hello, Ana! Hola, Bea!
Part 8 covers closures in depth.
Shadowing
An inner declaration with the same name as an outer one shadows it: inside the inner scope, the name refers to the inner variable, and the outer one is unreachable by that name.
const theme = "light";
function render() {
const theme = "dark"; // shadows the module-level theme
return theme;
}
console.log(render(), theme);
dark light
Shadowing is legal and sometimes useful, but it's a common source of confusion when the code inside also meant to use the outer value. Linters can flag it (no-shadow).
Loop and switch scopes
for loops with let or const get a scope for the header, and with let a new copy of the variable for each iteration (which is why closures in let loops work, article 26). The body is a separate, nested block:
for (let i = 0; i < 1; i++) {
let i = "body"; // legal: shadows the header's i
console.log(i);
}
body
switch is a trap: all the case clauses share one block. Declaring the same name in two cases is a SyntaxError, and a variable declared in one case is visible (but possibly uninitialized) in the others:
try {
eval(`switch (1) {
case 0: let status = "zero"; break;
case 1: status = "one"; // the case-0 let is in its dead zone here
}`);
} catch (err) {
console.log(err.name);
}
ReferenceError
The fix is to give each case its own block with braces: case 0: { let status = ...; break; }.
The temporal dead zone
let, const and class declarations are created when their scope begins (they're hoisted), but they're not initialized until the line with the declaration runs. The time between entering the scope and reaching the declaration is the temporal dead zone (TDZ). Any access during it throws a ReferenceError.
function demo() {
// TDZ for value starts here
const readValue = () => value; // defining the function is fine
try {
readValue(); // calling it now reads value in its TDZ
} catch (err) {
console.log("early:", err.name);
}
const value = 42; // TDZ ends
console.log("later:", readValue());
}
demo();
early: ReferenceError
later: 42
The dead zone is temporal: what matters is when the access happens, not where it's written. The function readValue mentions value above its declaration, but calling it after the declaration works.
Every case that throws:
const cases = {
"use before let": "{ console.log(a); let a = 1; }",
"typeof in the TDZ": "{ typeof b; let b = 1; }",
"self-reference": "{ let c = c + 1; }",
"default parameter": "(function (x = y, y = 1) {})()",
"class before declaration": "{ new Point(); class Point {} }",
};
for (const [label, code] of Object.entries(cases)) {
try {
eval(code);
} catch (err) {
console.log(label.padEnd(25), err.name);
}
}
use before let ReferenceError
typeof in the TDZ ReferenceError
self-reference ReferenceError
default parameter ReferenceError
class before declaration ReferenceError
Two cases deserve attention:
typeofisn't safe in the TDZ.typeofreturns"undefined"for names that don't exist at all, but throws for alet/constthat exists and hasn't been initialized yet.- The TDZ applies even when an outer variable has the same name. Once the inner scope declares the name, the inner (not yet initialized) variable shadows the outer one for the whole block:
const color = "red";
function paint() {
try {
console.log(color); // the inner color, still in its TDZ
} catch (err) {
console.log(err.name);
}
const color = "blue";
}
paint();
ReferenceError
This is the main reason the TDZ exists: with var, the same code would quietly print undefined, hiding a bug. The TDZ turns "used before it was ready" into an immediate, visible error, and it's what makes const meaningful (a const can never be observed without its value).
Choosing the right scope
- Declare variables in the smallest scope that needs them. Fewer lines can see them, so fewer lines can break them, and the garbage collector can free them sooner.
- Declare at the top of the block where you use them, which keeps you out of the TDZ naturally.
- Use modules so files don't share a global namespace.
- Avoid reusing outer names for different meanings.
Common questions
What's the difference between scope and context?
Scope is about which variables are visible, decided by where code is written. "Context" usually means the value of this, which depends on how a function is called. They're unrelated mechanisms; part 8 covers this.
Are function parameters in the function's scope?
Yes, with a subtlety: when parameters have default values, they get their own scope that's evaluated left to right before the body runs. That's why a default can use an earlier parameter ((a, b = a * 2)) but not a later one.
Is the TDZ a performance cost?
Engines eliminate the check whenever they can prove the variable is initialized, which is almost always. Don't avoid let/const for performance.
Can a block-level function declaration leak out of its block?
In strict mode (modules, classes, "use strict"), no: it's block-scoped like let. In sloppy-mode scripts, legacy web-compatibility rules (Annex B of the specification) also create a var-like binding in the enclosing function, so it can be visible outside the block. Write modules and this never matters.
Summary
- Scopes: global, module, function and block.
let/const/classare block-scoped;varis function-scoped. - Name lookups go outward through enclosing scopes, decided by where code is written (lexical scope). This is what makes closures work.
- Inner declarations shadow outer ones; the loop body is nested inside the loop header's scope; all
switchcases share one block. - The temporal dead zone: a
let/const/classexists from the start of its scope but throws aReferenceErroruntil its declaration runs. It's about time, not position, andtypeofdoesn't escape it. - Keep scopes small and declare at the top of the block.
Practice Questions
What does this print?
let x = 1;
{ console.log(x); let x = 2; }
Answer
It throws a ReferenceError. The inner let x shadows the outer x for the whole block, and the console.log runs while the inner x is in its temporal dead zone.
What does typeof undeclaredName return, and what about typeof x just before let x in the same block?
Answer
"undefined" for a name that's not declared anywhere, but a ReferenceError for x, which is declared and in its TDZ.
Does this work?
function f() {
return v;
}
const v = 5;
console.log(f());
Answer
Yes, it prints 5. f mentions v before its declaration, but f is called after v is initialized, and the TDZ is about time, not position.
Why does report() in the lexical-scope example return "module" rather than "caller"?
Answer
Functions look up names in the scopes surrounding where they're defined. report is defined at module level, so it finds the module's source, no matter which function calls it.
How do you fix a switch whose cases each declare let result?
Answer
Wrap each case's statements in braces so each gets its own block: case "a": { let result = 1; ... break; }. Alternatively, declare let result; once before the switch and assign it in each case.
Previous: var and Hoisting in JavaScript: Function Scope and Why let Replaced It
Next: Destructuring in JavaScript: Arrays, Objects, Defaults, Renaming and Nested Patterns

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.