Scope Hoisting and Closures in JavaScript Explained in Depth
A complete guide to JavaScript scope, hoisting and closures: how names resolve, what the engine creates before code runs and how closures keep state alive.

Almost every JavaScript bug that reads "x is not defined", "cannot access x before initialization" or "why is this always the last value" is a scope bug. The rules are short, and they are the same rules that make callbacks, modules, private state and most of functional programming work. This guide covers all of it in one place: the kinds of scope, how a name is found, what the engine does before the first line runs, what a closure is and what it costs. It is arranged as a field manual, with each section giving the rule, a runnable example with real output and the bug that the rule explains. Every snippet runs on Node.js 24 as an ES module, and the output shown is from the run. The shorter single-topic posts are linked where they go further, and this one is meant to be read start to finish once and then used as a reference.
The topic has a reputation for being hard that it does not deserve. Scope is a lookup: given a name, which variable does it refer to? Hoisting is a preparation step: before running a scope, the engine creates its names. A closure is a consequence: a function created inside a scope remembers that scope. With those three ideas in place, the strange outputs people collect, the loop that prints the same number, the variable that is undefined, the counter that works without a class, all have one-line explanations.
Scope is a lookup
When code uses a name, the engine looks for a variable of that name in the current scope. If it is not there, it looks in the enclosing scope, and then the next, until it finds one or reaches the outermost scope and gives up with a ReferenceError. The ordered list of scopes it walks is the scope chain, and the walk is the whole mechanism.
const level = "module";
function outer() {
const level = "outer";
function inner() {
return level;
}
return inner();
}
function other() {
return level;
}
console.log(outer(), other());
try {
console.log(unknownName);
} catch (error) {
console.log(error.name + ": " + error.message);
}
console.log(typeof unknownName);outer module
ReferenceError: unknownName is not defined
undefinedThe two functions use the same name and get different variables, because each was written inside a different scope. The lookup for unknownName found nothing and threw, and typeof is the one probe that is allowed to ask without throwing. Nothing in this lookup depends on how the functions are called, which is the point of the next section.
Lexical scope: written, not called
JavaScript uses lexical scope, which means the scope chain of a function is fixed by where the function is written in the source. Calling it from somewhere else changes nothing. This is the property that lets you read a function and know what its names mean, and it is the opposite of dynamic scope, where a callee sees the caller's variables.
const owner = "module";
function showOwner() {
return owner;
}
function callerA() {
const owner = "caller A";
return showOwner();
}
function callerB() {
const owner = "caller B";
return [showOwner(), (() => owner)()];
}
const handlers = [showOwner, callerA, callerB];
console.log(handlers.map((fn) => fn()));
setTimeout(showOwner, 0);
console.log(await new Promise((resolve) => setTimeout(() => resolve(showOwner()), 1)));[ 'module', 'module', [ 'module', 'caller B' ] ]
moduleEvery call to showOwner returned the module-level value, from any caller, and from a timer, because that is the scope it was written in. The arrow function inside callerB was written in callerB, so it sees that function's owner. If JavaScript were dynamically scoped, the first and second calls would print the callers' values, and every function would depend on its caller's variable names. The post on lexical scope and the scope chain has the longer treatment, and the one place where JavaScript is dynamic, this, is covered later in this guide.
The kinds of scope
JavaScript has four kinds of scope, and each is created by a particular construct.
| Scope | Created by | Holds |
|---|---|---|
| Global | The runtime | Built-ins, and in classic scripts the top-level var |
| Module | An ES module or a CommonJS file | Top-level declarations of the file |
| Function | A function, including its parameters | var, let, const, parameters |
| Block | { }, if, for, while, try, catch, switch | let, const, class |
A block does not hold a var, and a function holds everything declared inside it, including var inside nested blocks. That asymmetry is the root of the loop bug and the leaking variable, and the posts on block versus function scope and var, let and const go through it.
function scopes(flag) {
if (flag) {
var fromVar = "var";
let fromLet = "let";
const fromConst = "const";
class Local {}
}
return [typeof fromVar, typeof fromLet, typeof fromConst, typeof Local];
}
console.log(scopes(true), scopes(false));
{
const inside = "block";
var outside = "leaks";
}
console.log(typeof inside, outside);
for (var i = 0; i < 2; i++) {}
for (let j = 0; j < 2; j++) {}
console.log(i, typeof j);[ 'string', 'undefined', 'undefined', 'undefined' ] [ 'undefined', 'undefined', 'undefined', 'undefined' ]
undefined leaks
2 undefinedThe var survived the block, in both calls, and the other three did not. When the branch did not run, fromVar still existed with the value undefined, a fact explained by hoisting, below. The loop counters show the same split: i is visible after its loop and j is not. The practical rule is to use const and let and never var, so that a name lives exactly as long as the braces around it.
var, let and const: the decision
The three keywords differ on scope, on what they are before their line, on redeclaration and on reassignment.
var | let | const | |
|---|---|---|---|
| Scope | Function | Block | Block |
| Before its line | undefined | ReferenceError | ReferenceError |
| Redeclare in the same scope | Allowed | SyntaxError | SyntaxError |
| Reassign | Allowed | Allowed | TypeError |
The default we use is const for every binding, let when the code reassigns and no var. The reason is information: a reader who sees const knows the name never points elsewhere and can stop tracking it. const fixes the binding and not the value, so an object assigned to a const can still be changed, and Object.freeze is the tool for that, shallow as it is.
const user = { name: "Ada", tags: ["a"] };
user.name = "Grace";
user.tags.push("b");
try {
user = {};
} catch (error) {
console.log(error.name + ": " + error.message);
}
const frozen = Object.freeze({ list: [1] });
try {
frozen.list = [];
} catch (error) {
console.log(error.name);
}
frozen.list.push(2);
console.log(user, frozen);
for (const word of ["x", "y"]) {
console.log(word);
}TypeError: Assignment to constant variable.
TypeError
{ name: 'Grace', tags: [ 'a', 'b' ] } { list: [ 1, 2 ] }
x
yThe object was edited through the const binding, and only the rebinding failed. The frozen object refused a new property value and still allowed a push into its array, because the freeze is one level deep. A for...of loop can use const, because each iteration gets its own binding, which sets up the loop section below. Adopting the default is a lint change: no-var and prefer-const enforce it and the auto-fixer does most of the work.
How the engine models scope
It helps to hold a simple model of what the engine builds. Each scope is a record of names and their current values, with a link to the enclosing record. Running a function creates a record for that call, and the function's own link is the record where it was created, not where it is called, which is the lexical rule restated as data. A name lookup is a walk along the links.
Engines are free to optimize that model, and they do. A variable that no closure captures can live on the stack or in a register for the length of the call and never exist as an object. A variable that a closure captures is moved to a heap-allocated record that survives the call. Names that cannot be resolved statically, because eval or with is in play, force the engine back to the slow, dynamic model, which is part of why strict mode and modules prohibit them. None of this changes what your program does, and all of it changes how much memory a closure costs: the captured variables are the part that lives on, and an uncaptured one is free.
The model also explains what a stack trace shows. Each frame is one function call with its own record, and the frames you see in a trace are the calls that were active when the error happened. The scope chain of each one is separate from the call chain, which is why a function called from many places has one set of captured variables and many frames over its lifetime.
Hoisting: names exist before code runs
Before a scope runs, the engine creates every declaration in it. That preparation is called hoisting, and it does not move code. Each kind of declaration starts in a different state: a function declaration is created with its body, var is created as undefined, and let, const and class are created and left uninitialized.
console.log(add(2, 3));
console.log(typeof early, early);
function add(a, b) {
return a + b;
}
var early = "set later";
try {
multiply(2, 3);
} catch (error) {
console.log(error.name + ": " + error.message);
}
var multiply = function (a, b) {
return a * b;
};
try {
divide(6, 3);
} catch (error) {
console.log(error.name + ": " + error.message);
}
const divide = (a, b) => a / b;
function legacy() {
const first = typeof thing;
var thing = "a string";
function thing() {}
return [first, typeof thing];
}
console.log(legacy());5
undefined undefined
TypeError: multiply is not a function
ReferenceError: Cannot access 'divide' before initialization
[ 'function', 'string' ]The function declaration worked before its line, because it was created with its body. The var was there and undefined. A function expression stored in a var was not yet a function, which gives the confusing "is not a function", and the same function in a const gave the dead zone error instead. When a function and a var share a name, the function wins until the assignment runs. The post on hoisting covers each case, and the practical rule is to declare before use and let the linter enforce it.
The temporal dead zone
A let, const or class binding exists from the start of its block and cannot be touched until its declaration runs. The region in between is the temporal dead zone, and reading in it throws. The word temporal matters: the zone is about time, not position in the file.
function readConfig() {
return config.retries;
}
try {
readConfig();
} catch (error) {
console.log(error.name + ": " + error.message);
}
const config = { retries: 3 };
console.log(readConfig());
{
try {
console.log(label);
} catch (error) {
console.log(error.message);
}
const label = "inner";
}
function range(start = end - 10, end = 100) {
return [start, end];
}
try {
range();
} catch (error) {
console.log(error.message);
}
try {
console.log(typeof later);
let later = 1;
} catch (error) {
console.log(error.name);
}ReferenceError: Cannot access 'config' before initialization
3
Cannot access 'label' before initialization
Cannot access 'end' before initialization
ReferenceErrorThe first call to readConfig ran before the constant existed, and the second ran after. The shadowing block shows that the inner declaration blocks the outer name for the whole block. A default parameter that reads a later parameter lands in the zone too, and typeof does not protect against it. The dead zone is the language choosing a loud error over a silent undefined, and the post on the temporal dead zone lists the places it hides, including circular imports.
Closures: a function and its scope
When a function is created, it keeps a reference to the scope it was created in. If the function outlives the call that made the scope, the scope stays alive, and the function keeps access to its variables. That combination is a closure, and it needs no special syntax.
function makeCounter(start = 0) {
let count = start;
return {
increment() {
count += 1;
return count;
},
reset() {
count = start;
},
get value() {
return count;
},
};
}
const a = makeCounter();
const b = makeCounter(100);
a.increment();
a.increment();
b.increment();
console.log(a.value, b.value, typeof count);
a.reset();
console.log(a.value, b.value);2 101 undefined
0 101Each call to makeCounter creates a new count, and the three methods returned for it share that one variable. The two counters are independent, and nothing outside can reach count, because no name in an outer scope refers to it. This is the standard way to hide state in JavaScript, and it follows from lexical scope and nothing else: the methods were written inside makeCounter, so their chain includes its variables, and the chain stays alive as long as the methods do.
The shortest definition of a closure is that it is what lets a function remember where it came from. Every callback you have written is one: the function passed to setTimeout uses variables from the code around it, long after that code has returned.
function schedule(name, delay) {
const message = `hello from ${name}`;
return new Promise((resolve) => {
setTimeout(() => resolve(message), delay);
});
}
const results = await Promise.all([schedule("a", 5), schedule("b", 1), schedule("c", 3)]);
console.log(results);
const adders = [1, 10, 100].map((n) => (x) => x + n);
console.log(adders.map((add) => add(5)));
const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
const pipeline = compose((x) => x * 2, (x) => x + 1);
console.log(pipeline(5));[ 'hello from a', 'hello from b', 'hello from c' ]
[ 6, 15, 105 ]
12Each timer callback closed over its own message. The array of adders holds three functions that each closed over a different n. The compose helper returns a function that closes over the list of functions. Partial application, currying, decorators, middleware and event handlers are all closures wearing different names, and the posts on functions in this series build on that fact.
Closures in loops
The most famous scope bug is a loop that creates functions. A var loop variable is one binding for the whole loop, so every closure sees its final value. A let loop variable is a fresh binding for each iteration, copied from the previous one.
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
const withIife = [];
for (var k = 0; k < 3; k++) {
withIife.push(((captured) => () => captured)(k));
}
console.log(withVar.map((f) => f()), withLet.map((f) => f()), withIife.map((f) => f()));
const timers = [];
for (let n = 1; n <= 3; n++) {
timers.push(new Promise((resolve) => setTimeout(() => resolve(n * n), 4 - n)));
}
console.log(await Promise.all(timers));
for (const [index, name] of ["x", "y"].entries()) {
setTimeout(() => console.log(index, name), 0);
}
await new Promise((resolve) => setTimeout(resolve, 5));[ 3, 3, 3 ] [ 0, 1, 2 ] [ 0, 1, 2 ]
[ 1, 4, 9 ]
0 x
1 yThe var closures all returned 3. The let closures returned 0, 1 and 2, and the immediately invoked function, the old workaround, achieved the same by capturing the value as an argument. The timer example works because each n is its own binding, and for...of loops behave the same way. The conclusion is not to memorize the old workaround but to stop using var: the problem it solves no longer exists.
Immediately invoked functions and the module pattern
Before ES modules, a file could only hide its names by wrapping them in a function. The immediately invoked function expression created a scope, ran once and returned what it chose to expose. The pattern is a closure used as a namespace, and you will meet it in older code and in bundler output.
const Inventory = (function () {
const items = new Map();
let nextId = 1;
function validate(name, qty) {
if (typeof name !== "string" || name.trim() === "") throw new TypeError("name required");
if (!Number.isInteger(qty) || qty < 0) throw new RangeError("qty must be a non-negative integer");
}
return {
add(name, qty) {
validate(name, qty);
const id = nextId++;
items.set(id, { id, name, qty });
return id;
},
total() {
let sum = 0;
for (const item of items.values()) sum += item.qty;
return sum;
},
names() {
return [...items.values()].map((item) => item.name);
},
};
})();
Inventory.add("pen", 10);
Inventory.add("ink", 4);
try {
Inventory.add("", 1);
} catch (error) {
console.log(error.name);
}
console.log(Inventory.total(), Inventory.names(), typeof Inventory.items, typeof validate);TypeError
14 [ 'pen', 'ink' ] undefined undefinedThe helper validate, the map and the counter are invisible from outside, and only the three methods are reachable. The function runs once, so the object is a singleton, the same property that an ES module's top level has. A module does it with less ceremony: top-level declarations are private unless exported, and the module runs once. The old pattern is still a handy way to make a throwaway scope in a script, and a block with const does the same job today.
Private state
Closures are how JavaScript hid data before private fields existed, and they remain a good choice for small factories. The variable is reachable only through the functions that close over it.
function createAccount(opening) {
let balance = opening;
const history = [];
function record(kind, amount) {
history.push({ kind, amount, balance });
}
return Object.freeze({
deposit(amount) {
if (amount <= 0) throw new RangeError("amount must be positive");
balance += amount;
record("deposit", amount);
return balance;
},
withdraw(amount) {
if (amount > balance) throw new RangeError("insufficient funds");
balance -= amount;
record("withdraw", amount);
return balance;
},
get balance() {
return balance;
},
statement() {
return history.map((entry) => `${entry.kind} ${entry.amount} -> ${entry.balance}`);
},
});
}
const account = createAccount(100);
account.deposit(50);
account.withdraw(30);
try {
account.withdraw(1000);
} catch (error) {
console.log(error.message);
}
console.log(account.balance, account.statement(), Object.keys(account));
try {
account.balance = 999;
} catch (error) {
console.log(error.name);
}
console.log(account.balance);insufficient funds
120 [ 'deposit 50 -> 150', 'withdraw 30 -> 120' ] [ 'deposit', 'withdraw', 'balance', 'statement' ]
TypeError
120The balance and history are not properties of the object, so nothing can change them except the methods, and the assignment at the end threw a TypeError, because balance is a getter with no setter and a module is strict. The balance stayed at 120. The cost compared with a class is that every account creates its own copies of the four functions, where a class shares them through the prototype. For a handful of objects that is nothing, and for a hundred thousand it is memory, which is where a class with #private fields, covered in the post on private fields, is the better tool.
Partial application and currying
A closure that fixes some arguments and waits for the rest is partial application. It is the cleanest example of closures as a tool and not only a mechanism, because the result is a new function made from an old one.
const partial = (fn, ...fixed) => (...rest) => fn(...fixed, ...rest);
const curry = (fn) => {
const curried = (...args) => (args.length >= fn.length ? fn(...args) : (...more) => curried(...args, ...more));
return curried;
};
const volume = (width, height, depth) => width * height * depth;
const withWidth = partial(volume, 2);
const curriedVolume = curry(volume);
console.log(withWidth(3, 4), curriedVolume(2)(3)(4), curriedVolume(2, 3)(4), curriedVolume(2)(3, 4));
const formatMoney = (currency, locale, amount) =>
new Intl.NumberFormat(locale, { style: "currency", currency }).format(amount);
const usd = partial(formatMoney, "USD", "en-US");
const eur = curry(formatMoney)("EUR")("de-DE");
console.log(usd(1234.5), eur(1234.5).replace(/\s/g, " "));
const prices = [5, 12.5, 100];
console.log(prices.map(usd));
console.log(["1", "2", "3"].map(parseInt), ["1", "2", "3"].map(Number), ["1", "2", "3"].map((s) => parseInt(s, 10)));24 24 24 24
$1,234.50 1.234,50 €
[ '$5.00', '$12.50', '$100.00' ]
[ 1, NaN, NaN ] [ 1, 2, 3 ] [ 1, 2, 3 ]The fixed arguments live in the closure, and each call supplies the rest. A configured formatter is built once and reused, which is what a decorator or a factory does too. A known trap appears in the last line: passing parseInt directly to map gives it the index as a radix, so ["1","2","3"].map(parseInt) is [1, NaN, NaN], and a wrapper that fixes the radix, or Number, is the safe form. Currying relies on fn.length, which counts only the parameters before the first default or rest, so it does not work for functions with optional parameters.
Closures that cache: memoize and once
A closure can hold a cache, which turns a function into one that remembers its answers.
function memoize(fn) {
const cache = new Map();
let hits = 0;
const wrapper = (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) {
hits += 1;
return cache.get(key);
}
const value = fn(...args);
cache.set(key, value);
return value;
};
wrapper.stats = () => ({ size: cache.size, hits });
return wrapper;
}
let calls = 0;
const slowSquare = (n) => {
calls += 1;
return n * n;
};
const fast = memoize(slowSquare);
console.log(fast(4), fast(4), fast(5), fast(4));
console.log(calls, fast.stats());
function once(fn) {
let done = false;
let result;
return (...args) => {
if (!done) {
done = true;
result = fn(...args);
}
return result;
};
}
const init = once(() => {
calls += 100;
return "initialized";
});
console.log(init(), init(), calls);16 16 25 16
2 { size: 2, hits: 2 }
initialized initialized 102The memoized function computed each distinct input once, and the cache and the hit counter are invisible variables inside the closure. once is the same idea with a flag. Two cautions apply: a cache that is never trimmed grows without bound, as covered in the post on garbage collection, and a key built with JSON.stringify cannot distinguish arguments that serialize alike, such as undefined and null. For a cache keyed by an object, a WeakMap is the safe choice, as shown in the post on WeakMap and WeakSet.
Closures that wait: debounce and throttle
Timers are the natural home of closures, because the callback outlives the call that scheduled it. A debounce delays a function until calls stop arriving, and the pending timer lives in the closure.
function debounce(fn, wait) {
let timer;
let calls = 0;
const debounced = (...args) => {
calls += 1;
clearTimeout(timer);
timer = setTimeout(() => fn(...args, calls), wait);
};
debounced.cancel = () => clearTimeout(timer);
return debounced;
}
const log = [];
const save = debounce((value, count) => log.push(`${value} after ${count} calls`), 10);
save("a");
save("b");
save("c");
await new Promise((resolve) => setTimeout(resolve, 30));
save("d");
await new Promise((resolve) => setTimeout(resolve, 30));
const cancelled = debounce(() => log.push("never"), 10);
cancelled();
cancelled.cancel();
await new Promise((resolve) => setTimeout(resolve, 20));
console.log(log);[ 'c after 3 calls', 'd after 4 calls' ]Three rapid calls produced one invocation with the last value, and a later call produced another. The cancelled debounce never fired, because its timer was cleared. The timer variable is private to each debounced function, so two debounced functions do not interfere. A debounce that is created inside a render function, or on every event, creates a new closure and a new timer each time and does not debounce anything, a common bug with a simple cause: the closure must be created once and reused.
Closures and asynchronous code
Async code is where closures are used the most and where their live-variable behavior bites hardest. A closure sees the current value of the variable it captured, not the value at the time it was created, and by the time an async callback runs, the variable may have moved on.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function sequentialLoop(ids) {
const seen = [];
for (const id of ids) {
await sleep(2);
seen.push(id);
}
return seen;
}
async function sharedState() {
let current = "start";
const readers = [];
for (const id of ["a", "b", "c"]) {
current = id;
readers.push(sleep(1).then(() => current));
}
return Promise.all(readers);
}
async function capturedState() {
const readers = [];
for (const id of ["a", "b", "c"]) {
const captured = id;
readers.push(sleep(1).then(() => captured));
}
return Promise.all(readers);
}
console.log(await sequentialLoop([1, 2, 3]));
console.log(await sharedState());
console.log(await capturedState());
let latest = 0;
const results = [];
async function fetchLike(query, delay) {
await sleep(delay);
return `result for ${query}`;
}
async function search(query, delay) {
const myRequest = ++latest;
const result = await fetchLike(query, delay);
if (myRequest === latest) results.push(result);
}
await Promise.all([search("a", 6), search("ab", 1), search("abc", 3)]);
console.log(results);[ 1, 2, 3 ]
[ 'c', 'c', 'c' ]
[ 'a', 'b', 'c' ]
[ 'result for abc' ]The first function ran one step at a time. The second function's closures all read current after the loop had finished, so every reader returned the last value, and the third captured a per-iteration value and returned its own. The last example is the standard guard against a stale response: each call remembers its own request number in a closure, and compares it with the latest when the answer arrives, so a slow response to an old query is dropped. The same idea, a closure over a token, is how cancellation and "ignore this result" are implemented in practice.
A related hazard is a closure that outlives the component or request that created it, and then writes into state that belongs to something else. When a callback captures a variable that another part of the program reassigns, the callback and the code that assigns it are coupled, and the coupling is invisible from either side. The remedy is the same in every case: capture a value when you want a value, and capture a mutable box, an object with a field, when you want to share a change on purpose and make the sharing visible.
Closures and memory
A closure keeps alive every variable it references, and in some engines the whole scope that contains them. That is the right behavior for state, and an expensive one when the closure outlives its purpose and captures something large.
function makeHandlerLean(document) {
const summary = document.text.slice(0, 10);
return () => summary;
}
function makeHandlerHeavy(document) {
return () => document.text.slice(0, 10);
}
const registry = [];
const big = { text: "x".repeat(1_000_000) };
registry.push(makeHandlerLean(big), makeHandlerHeavy(big));
console.log(registry.map((handler) => handler().length));
const listeners = new Set();
function subscribe(callback) {
listeners.add(callback);
return () => listeners.delete(callback);
}
const unsubscribers = [];
for (let i = 0; i < 100; i++) {
const payload = new Array(1000).fill(i);
unsubscribers.push(subscribe(() => payload.length));
}
console.log(listeners.size);
unsubscribers.forEach((off) => off());
console.log(listeners.size);[ 10, 10 ]
100
0Both handlers return the same ten characters. The lean one captured a short string, so the large document can be freed once nothing else holds it. The heavy one captured the document itself, and keeps a million characters alive as long as the handler lives. The subscription example shows the other half: each callback holds a thousand-element array, and until it is unsubscribed the set holds it. Extract what a long-lived closure needs into small values, and always return an unsubscribe function from anything that registers a callback. The post on garbage collection lists the other common retention patterns.
The stale closure problem in event handlers
User interface code creates handlers whenever it renders, and each handler closes over the values of that render. When a long-lived handler is registered once and reads a variable that later renders replace, it keeps using the value it first saw. The problem has a name in front-end work, the stale closure, and the cause is the lexical rule applied to a variable that was replaced and not mutated.
function createStore(initial) {
let state = initial;
const listeners = new Set();
return {
get: () => state,
set(next) {
state = next;
listeners.forEach((fn) => fn(state));
},
subscribe: (fn) => (listeners.add(fn), () => listeners.delete(fn)),
};
}
const store = createStore({ count: 0 });
const log = [];
function makeHandlerStale(snapshot) {
return () => log.push(`stale sees ${snapshot.count}`);
}
function makeHandlerLive() {
return () => log.push(`live sees ${store.get().count}`);
}
const stale = makeHandlerStale(store.get());
const live = makeHandlerLive();
store.set({ count: 1 });
store.set({ count: 2 });
stale();
live();
store.subscribe((state) => log.push(`subscriber got ${state.count}`));
store.set({ count: 3 });
console.log(log);
const ref = { current: 0 };
const readRef = () => ref.current;
ref.current = 5;
console.log(readRef());[ 'stale sees 0', 'live sees 2', 'subscriber got 3' ]
5The stale handler captured the object that was current when it was made, and the store replaced the state with new objects, so the handler still saw the first one. The live handler asked the store each time, and the subscriber was called with each new value. The last lines show the third remedy, a mutable box: an object whose field changes while the box itself stays put, so a closure over the box always reads the latest. Framework hooks for "latest value" references are this pattern with a name.
The rule of thumb for handlers that live longer than one render is to give them a way to read the current value, through a store, a getter or a box, instead of capturing a value that will be replaced. And unsubscribe handlers when their owner goes away, so that closures do not keep a dead component's state alive.
this is the exception
Everything above is lexical. this is not. For an ordinary function, this is decided by how the function is called, and for an arrow function it comes from the enclosing scope like any other variable. That split is the main reason arrow functions exist.
const timer = {
label: "tick",
start() {
const regular = [1, 2].map(function () {
return this === undefined ? "lost" : this.label;
});
const arrow = [1, 2].map(() => this.label);
return { regular, arrow };
},
};
console.log(timer.start());
const detached = timer.start;
try {
detached();
} catch (error) {
console.log(error.name);
}
class Button {
label = "Save";
handleArrow = () => this.label;
handleMethod() {
return this.label;
}
}
const { handleArrow, handleMethod } = new Button();
console.log(handleArrow());
try {
handleMethod();
} catch (error) {
console.log(error.name);
}{ regular: [ 'lost', 'lost' ], arrow: [ 'tick', 'tick' ] }
TypeError
Save
TypeErrorThe ordinary callback inside map was called with no receiver, so this was undefined. The arrow took this from start. Detaching start from its object lost the receiver and made even the arrow fail, because the enclosing this was gone, and the class field arrow survived being detached because it was bound at construction. The post on the this keyword lists the four call rules. A reliable habit is to ask, for every function you pass somewhere, whether it uses this, and if so to bind it or use an arrow that closes over the right one.
Scope in modules
An ES module has its own top-level scope. A top-level var or function does not become a property of the global object, top-level this is undefined and the module's variables are private unless exported. Exports are live bindings, which is a kind of closure over the exporting module's scope.
var topLevelVar = 1;
function topLevelFunction() {}
console.log(typeof globalThis.topLevelVar, typeof globalThis.topLevelFunction, typeof this);
const counter = await import(
"data:text/javascript," +
encodeURIComponent(`
let count = 0;
export const read = () => count;
export function increment() { count++; }
export { count };
`)
);
console.log(counter.count, counter.read());
counter.increment();
console.log(counter.count, counter.read());undefined undefined undefined
0 0
1 1Nothing leaked to the global object, and this was undefined. The importer saw the exporter's variable change through both the function and the live binding, with the variable private to the module. This is why modules replaced the old pattern of wrapping a file in an immediately invoked function to avoid globals. The posts on ES modules and globalThis cover the details.
Strict mode and accidental globals
In a sloppy script, assigning to a name that was never declared creates a global variable, and a typo becomes a new global. Strict mode, which ES modules and class bodies use automatically, turns that into a ReferenceError.
const sloppy = new Function("totl = 10; return typeof totl;");
console.log(sloppy(), typeof totl);
const strict = new Function("'use strict'; totl2 = 10;");
try {
strict();
} catch (error) {
console.log(error.name + ": " + error.message);
}
console.log(typeof globalThis.totl, delete globalThis.totl);number number
ReferenceError: totl2 is not defined
number trueThe sloppy function created a global, and the strict one refused. Accidental globals are shared by every script in a page, which is how two unrelated loops using an undeclared i corrupt each other. Modules and strict mode remove the whole class of bug, and the post on strict mode lists the other changes.
Shadowing and naming
An inner declaration with the same name as an outer one hides it for the inner scope. Shadowing is legal and sometimes intentional, and it is also a source of confusion when a parameter hides a module-level variable.
const value = "outer";
function show(value) {
return value;
}
function nested() {
const value = "function";
{
const value = "block";
return [value, show("argument")];
}
}
console.log(show(), nested());
const total = 10;
function tally(items) {
let total = 0;
for (const item of items) {
total += item;
}
return total;
}
console.log(tally([1, 2, 3]), total);undefined [ 'block', 'argument' ]
6 10The first call used the parameter, which was undefined, and not the module-level value. Inside the function the block's declaration won. Three different bindings shared one name, and each use found the nearest. The ESLint rule no-shadow reports shadowing, and the usual fix is a more specific name for the inner variable. A parameter that is shadowed by a local of the same name is the case that hides real bugs.
Switch, catch and the smaller scopes
Several constructs have a scope of their own that is easy to forget. A switch is one block for all its cases, a catch clause has a scope for its parameter, and a function declaration in a block is block scoped in strict code.
function render(kind) {
switch (kind) {
case "a": {
const text = "alpha";
return text;
}
case "b": {
const text = "beta";
return text;
}
default:
return "none";
}
}
console.log(render("a"), render("b"), render("z"));
try {
new Function(`switch (1) { case 1: const x = 1; break; case 2: const x = 2; break; }`);
} catch (error) {
console.log(error.name);
}
try {
throw new Error("failure");
} catch (error) {
var leaked = "var survives";
}
console.log(typeof error, leaked);
{
function inBlock() {
return "block function";
}
console.log(inBlock());
}
console.log(typeof inBlock);alpha beta none
SyntaxError
undefined var survives
block function
undefinedBraces around each case gave each its own scope, and without them the duplicate names were a syntax error. The catch parameter was not visible after the clause, while a var inside it survived. And in an ES module, the function declared in a block does not exist outside it. The posts on switch statements and block scope go through each.
Generators keep their scope alive
A generator function is a closure with a pause button. Its local variables stay alive between calls to next(), so it can hold state without a class or an outer variable.
function* idGenerator(prefix) {
let n = 0;
while (true) {
const reset = yield `${prefix}-${++n}`;
if (reset) n = 0;
}
}
const ids = idGenerator("order");
console.log(ids.next().value, ids.next().value, ids.next(true).value, ids.next().value);
function* take(iterable, count) {
let taken = 0;
for (const value of iterable) {
if (taken++ >= count) return;
yield value;
}
}
const other = idGenerator("inv");
console.log([...take(other, 3)], other.next().value);
function* withCleanup() {
try {
yield 1;
yield 2;
} finally {
console.log("generator cleanup ran");
}
}
for (const value of withCleanup()) {
console.log("got", value);
break;
}order-1 order-2 order-1 order-2
[ 'inv-1', 'inv-2', 'inv-3' ] undefined
got 1
generator cleanup ranThe counter variable lived inside the generator and survived between calls, and passing a value into next(true) reset it. The take helper stopped a source that never ends, and by leaving its loop it closed the source, so the later next() on other returned undefined. Breaking out of the for...of closed the generator, which ran its finally, so cleanup attached to the generator's scope runs when the loop ends early, as covered in the post on iterators. A suspended generator holds its frame in memory until it finishes or is closed, which is another way a closure can retain more than it appears to.
Scope in classes
A class body creates its own scope, and the rules for names inside it have a few particulars. Methods are written in the class scope, so they see names declared outside the class and the class's own name. Field initializers run once per instance in a scope that can see this. And a static initialization block runs once, in a scope of its own, where var and let do not leak into the class body.
const prefix = "outer";
class Report {
static #count = 0;
static defaults;
static {
const base = { title: "untitled", rows: 0 };
Report.defaults = Object.freeze(base);
}
title = Report.defaults.title + "-" + prefix;
#id = ++Report.#count;
describe = () => `${this.title} #${this.#id}`;
rename(title) {
this.title = title;
return this;
}
static get created() {
return Report.#count;
}
}
const first = new Report();
const second = new Report().rename("sales");
console.log(first.describe(), second.describe(), Report.created);
console.log(typeof base, Object.isFrozen(Report.defaults));
const { describe } = second;
console.log(describe());untitled-outer #1 sales #2 2
undefined true
sales #2The field initializer used the outer constant and a static, the static block's base was not visible outside it, and the arrow field closed over the instance, so it survived being detached. Class bodies are always strict, and class declarations have a dead zone like let. The post on classes and the post on static members go through the rest.
Debugging a scope problem
When a name has the wrong value or does not exist, four checks find the cause. First, find the declaration: which scope is it in, and is the use inside the braces of that scope? Second, check for shadowing: is a nearer declaration hiding the one you meant? Third, check timing: is the use before the declaration in the same scope, which puts it in the dead zone, or does a closure read it after it changed? Fourth, check the loop: does a callback created in a loop read a variable that the loop keeps changing?
The debugger makes the chain visible. In Chrome DevTools and in Node.js with --inspect, pausing at a breakpoint shows a Scope panel that lists the local, closure and global scopes in chain order with their values. A debugger statement pauses where you put it. For a quick look from code, printing the value and its type together answers most questions, and the typeof operator tells you whether a name exists at all.
function trace(label, read) {
try {
const value = read();
console.log(label.padEnd(18), typeof value, JSON.stringify(value));
} catch (error) {
console.log(label.padEnd(18), error.name);
}
}
let counter = 0;
const bump = () => ++counter;
trace("before bump", () => counter);
bump();
trace("after bump", () => counter);
trace("undeclared", () => missing);
trace("dead zone", () => later);
const later = 1;
trace("after dead zone", () => later);before bump number 0
after bump number 1
undeclared ReferenceError
dead zone ReferenceError
after dead zone number 1A small helper that reads a variable inside a function reports the three states a name can be in: a value, a failure from a missing declaration and a failure from the dead zone. Wrapping the read in a function matters, because it delays the lookup until trace runs, which is what a closure is for.
A worked example: a rate limiter made of closures
Three pieces of this guide, private state, a captured clock and a returned function, come together in a small utility that appears in nearly every service. A rate limiter allows a fixed number of calls in a window, and each limiter keeps its own counters. The version below injects its clock, so the behavior can be checked without waiting.
function createRateLimiter({ limit, windowMs, now = Date.now }) {
const hits = new Map();
function prune(key, current) {
const recent = (hits.get(key) ?? []).filter((time) => current - time < windowMs);
hits.set(key, recent);
return recent;
}
return {
allow(key) {
const current = now();
const recent = prune(key, current);
if (recent.length >= limit) return false;
recent.push(current);
return true;
},
remaining(key) {
return Math.max(0, limit - prune(key, now()).length);
},
keys: () => [...hits.keys()],
};
}
let clock = 0;
const limiter = createRateLimiter({ limit: 2, windowMs: 1000, now: () => clock });
const other = createRateLimiter({ limit: 1, windowMs: 1000, now: () => clock });
const trace = [];
for (const [time, key] of [[0, "a"], [100, "a"], [200, "a"], [200, "b"], [1100, "a"], [1150, "a"]]) {
clock = time;
trace.push(`${time} ${key} ${limiter.allow(key) ? "allowed" : "blocked"}`);
}
console.log(trace);
console.log(limiter.remaining("a"), limiter.remaining("b"), other.remaining("a"), limiter.keys());[
'0 a allowed',
'100 a allowed',
'200 a blocked',
'200 b allowed',
'1100 a allowed',
'1150 a allowed'
]
0 1 1 [ 'a', 'b' ]Each limiter owns its map, and the two limiters do not share counters. The clock is a function passed in and captured, which is what makes the test above run in microseconds: advancing a variable stands in for time passing. The third call from a was blocked, and after the window slid past, the oldest hits aged out and two more were allowed. A real limiter would also drop keys whose lists are empty so the map does not grow forever, and would live behind a shared store if the service runs on several machines. The closure structure, private state plus injected dependencies, is the shape to reach for whenever you write something stateful that must be testable.
Reading scope in unfamiliar code
A procedure helps when you open a file you did not write and need to know what a name means. Start at the use and find the nearest enclosing function or block. Look for a declaration in it, including parameters and the loop head. If there is none, move out one level and repeat until you reach the top of the module. Note any var, because it belongs to the whole function and not to the block you found it in. Note any function that is returned or stored, because it is a closure and its variables outlive the call. And note any callback passed to a timer, a listener or a promise, because it runs later and sees the variables as they are then.
Three signs deserve a second look. A name used far above its declaration in the same file is relying on hoisting or on being called late. A loop that creates functions needs a check of the keyword in its head. And a variable that is assigned in one function and read in another is shared state, and the closure between them is the coupling that a refactor will break. Writing the answer to "which variable is this" next to a tricky line is a quick way to test your reading, and a code review comment that asks it is usually welcome.
Patterns that use closures
A few patterns recur, and each is a closure with a job. A factory builds objects with private state. A decorator wraps a function and adds behavior around it. A callback or subscription holds the context of its creator. A module-level variable is a closure over the module scope. A generator keeps its local variables alive between calls. And an iterator, a promise executor and an event handler are all functions that were created in one scope and run in another.
| Pattern | What the closure holds | Risk to watch |
|---|---|---|
| Factory with private state | The state variables | A copy of every method per instance |
| Memoize | A cache | Unbounded growth |
| Debounce, throttle | A timer and the last arguments | Creating a new one on every call |
| Event handler or subscription | The surrounding variables | Never being removed |
| Partial application | The fixed arguments | None, usually |
| Generator | The suspended frame | Forgetting to close it |
The choice between a closure and a class is mostly about scale and shape. A closure is the lighter tool for one or a few objects and for single-purpose helpers, and a class is better when there are many instances, when the methods should be shared and when inheritance or instanceof matters.
A catalogue of scope bugs
The same few bugs account for most scope problems, and each has a short fix.
| Symptom | Cause | Fix |
|---|---|---|
| Every callback in a loop sees the last value | var loop variable shared by closures | Use let or const in the loop head |
Cannot access 'x' before initialization | Reading a let, const or class too early | Declare before use, or call later |
x is not a function on a hoisted name | A var function expression called before its assignment | Use a function declaration or define first |
A variable is undefined instead of an error | var hoisting | Replace var with let or const |
| A new global appears | Assignment to an undeclared name in sloppy code | Use modules and strict mode |
this is undefined in a callback | A method passed without its receiver | Arrow function, bind or a class field arrow |
| Memory grows with a long-lived callback | The closure captures a large object | Capture only what you need, unsubscribe |
| Two debounced functions interfere, or none debounces | A shared or recreated closure | Create once, keep per instance |
| A switch case throws on a repeated name | One scope for all cases | Braces around each case |
| A value is stale in a callback | The closure captured a variable that changed | Capture the value, or read the current one on purpose |
const stale = [];
let current = "first";
stale.push(() => current);
current = "second";
const captured = ((value) => () => value)(current);
current = "third";
console.log(stale[0](), captured());
function makeLogger(prefix) {
return (message) => `${prefix}: ${message}`;
}
const info = makeLogger("info");
const warn = makeLogger("warn");
console.log(info("a"), warn("b"));third second
info: a warn: bThe first closure read the variable when it was called, and so saw the latest value, while the second captured the value at creation. Which one is wanted depends on the case, and the bug appears when the author assumed the other one. A closure over a variable sees changes, and a closure over a parameter value does not.
Testing code that relies on closures
Closures are easy to test through their public behavior, and the tests that matter check independence, reset and the cost of retention. Each instance created by a factory should have its own state. Functions created in a loop should return their own values. A subscription should stop calling its callback after unsubscribing.
import { test } from "node:test";
import assert from "node:assert/strict";
function makeCounter() {
let count = 0;
return { next: () => ++count, peek: () => count };
}
function subscribable() {
const callbacks = new Set();
return {
subscribe: (fn) => {
callbacks.add(fn);
return () => callbacks.delete(fn);
},
emit: (value) => callbacks.forEach((fn) => fn(value)),
size: () => callbacks.size,
};
}
test("each counter keeps its own state", () => {
const a = makeCounter();
const b = makeCounter();
a.next();
a.next();
assert.equal(a.peek(), 2);
assert.equal(b.peek(), 0);
});
test("loop closures see their own value", () => {
const fns = [];
for (let i = 0; i < 3; i++) fns.push(() => i);
assert.deepEqual(fns.map((fn) => fn()), [0, 1, 2]);
});
test("unsubscribing releases the callback", () => {
const bus = subscribable();
const seen = [];
const off = bus.subscribe((value) => seen.push(value));
bus.emit(1);
off();
bus.emit(2);
assert.deepEqual(seen, [1]);
assert.equal(bus.size(), 0);
});Run it with node --test on Node.js 24. The second test would fail if the loop were rewritten with var, which makes it a useful guard against a regression in the oldest bug in the language. The third test asserts the size of the callback set, which is how a leak is caught before it reaches production.
A short list of rules to keep
If you remember only a few lines from this guide, remember these. Declare with const, use let when you must reassign and never write var. Declare before use. Put each case body in braces. Create functions in loops with a let or const loop variable, and expect them to see their own value. Capture a value when you want a value and a box when you want sharing. Return an unsubscribe function from anything that registers a callback. Prefer arrow functions for callbacks inside methods and methods for object methods. And when a name behaves oddly, find its declaration, check for shadowing and ask when the code runs relative to when the variable changes. Those eight habits remove nearly every scope bug we have met.
Where these rules stop
Scope rules describe names, not values. Two closures that share a variable share its current value, and nothing in the language tells them when it changes, so a closure that reads shared mutable state is a source of races in async code. A closure also cannot see variables that it does not mention, and eval and with, which break that guarantee, are forbidden in strict mode and modules. Finally, the scope chain is a model, and engines optimize it heavily: a variable that is never captured may live in a register and never exist as a heap object, and one that is captured is moved to the heap. You cannot observe the difference, and you should not design around it. Measure before changing code for performance reasons.
The rules are defined in the specification under environment records and execution contexts, and MDN's closures guide and its pages on scope and hoisting are the readable companions.


