Sub topic 11
Closures: Functions That Remember Their Scope
This chapter assumes you know how the scope chain resolves a name by walking outward from the current scope. It also assumes you can tell function scope from block scope with let and const. Here, that lookup model is extended to a new case: a function that runs after the scope it was written in has finished.
What a Closure Is
A closure is a function together with a reference to the scope where it was defined. Every JavaScript function is a closure in this sense. The behavior only becomes visible when a function outlives its parent scope. For example, an outer function returns an inner function, and the inner one is called later.
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2When makeCounter() returns, its local variable count would normally be gone. Nothing outside the function can name it. The returned function still refers to count, though, so the engine keeps that scope alive. Each call to next() reads and updates the same count.
This is lexical scope in action. The inner function looks up count in the place where it was written, not in the place where it is called. At the call site next() sits in the global scope, where no count exists, and the lookup still succeeds.
How It Works Internally
The ECMAScript specification describes scopes as environment records. An environment record is an object-like structure that holds the bindings of one scope and points to its outer environment. When a function object is created, the engine stores the current environment in an internal slot called [[Environment]].
A call to that function creates a fresh environment for the call. The new environment's outer pointer is set to the function's saved [[Environment]], not to the caller's environment. That single rule explains closures, and it explains lexical scoping in general.
As long as something reachable, such as the global binding next, refers to the function object, the makeCounter environment stays reachable too. The garbage collector cannot free it.
Closures Capture Variables, Not Values
A closure keeps a reference to the binding itself. It does not copy the value the variable held when the function was created. If the variable changes later, the closure sees the new value.
let message = "hello";
function show() {
return message;
}
message = "goodbye";
console.log(show()); // "goodbye"The function show was created while message was "hello", and it still returns "goodbye". The lookup happens when show runs, against the live binding.
The same applies to bindings inside a returned function's parent scope:
function makeGreeter() {
let name = "Ada";
const greet = () => `Hi, ${name}`;
name = "Grace";
return greet;
}
console.log(makeGreeter()()); // "Hi, Grace"The arrow function was created before name was reassigned. The binding had changed by the time it ran, so it reports "Grace".
Each Call Creates a Separate Environment
Every call to the outer function creates a new environment. Closures produced by different calls therefore have independent state.
function makeCounter() {
let count = 0;
return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
console.log(a()); // 1
console.log(a()); // 2
console.log(b()); // 1
console.log(a()); // 3Here a and b are built from the same source code. Each one holds a different count.
Closures From the Same Call Share State
When one call creates several functions, all of them point to the same environment. A change made through one is visible through the others.
function makeAccount(initial) {
let balance = initial;
return {
deposit(amount) {
balance += amount;
return balance;
},
withdraw(amount) {
if (amount > balance) {
throw new RangeError("Insufficient funds");
}
balance -= amount;
return balance;
},
getBalance() {
return balance;
},
};
}
const account = makeAccount(100);
account.deposit(50);
account.withdraw(30);
console.log(account.getBalance()); // 120
console.log(account.balance); // undefinedThe three methods share one balance. Code outside makeAccount cannot read or change balance directly. account.balance is undefined because balance is a variable, not a property. Every change has to go through the methods, so withdraw can enforce its rule. This is the module pattern: closures used for private state. Before ES modules and #private class fields existed, it was the main way to hide data in JavaScript.
Using Closures Deliberately
Closures show up in everyday code wherever a function needs some configuration or context that it should not take as an argument on every call.
Function factories
A factory takes some settings and returns a function that is fixed to those settings.
function makeMultiplier(factor) {
return (n) => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log([1, 2, 3].map(double)); // [2, 4, 6]
console.log([1, 2, 3].map(triple)); // [3, 6, 9]Parameters are ordinary bindings in the function's environment, so factor is captured the same way a let would be.
Callbacks that need context
Event handlers, timers, and promise callbacks run later, after the code that set them up has moved on. Closures let these callbacks reach the variables they need.
function delayedLog(label, ms) {
const start = Date.now();
setTimeout(() => {
console.log(`${label} after ${Date.now() - start} ms`);
}, ms);
}
delayedLog("tick", 100); // e.g. "tick after 101 ms"When the timer fires, delayedLog has already returned. The arrow function still reads label and start from that call's environment.
Run-once wrappers
A closure can hold a flag that survives between calls.
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}
const init = once(() => {
console.log("initializing");
return 42;
});
console.log(init()); // "initializing", then 42
console.log(init()); // 42Gotchas and Failure Modes
Stale reads are really live reads
A common surprise is a closure that seems to show an outdated value, or a value that is newer than expected. Both cases come from the same rule: the closure reads the binding when it runs. If you expected a snapshot and got the current value, you captured a variable that kept changing. If you expected the current value and got an old one, the closure is probably reading a different binding. A frequent cause is a fresh binding per call or per iteration that has since gone out of use, while the newer values live in other bindings.
Closures keep memory alive
A closure keeps its whole environment chain reachable for as long as the closure itself is reachable. Large objects referenced from that environment cannot be collected.
function attachHandler(button) {
const bigData = new Array(1_000_000).fill(0);
button.onclick = () => {
console.log(bigData.length);
};
}As long as the handler stays attached, bigData stays in memory. Engines such as V8 usually keep only the variables a closure actually references. However, all closures created in the same scope may share one environment object. In that case, a large variable used by one short-lived closure can be kept alive by a long-lived sibling closure. When a callback lives a long time, copy just the values it needs into small variables, or set large references to null once you are done with them.
`this` and `arguments` are not ordinary variables
Regular functions get their own this and arguments for each call, so an inner regular function does not see the outer function's this. Arrow functions have no this binding of their own. They resolve this lexically, the same way a closure resolves a variable. This is why arrow functions are the usual choice for callbacks inside methods.
When to Reach for a Closure
| Need | Closure fit | Alternative |
|---|---|---|
| Private state shared by a few functions | Good | Class with `#private` fields |
| Preconfigured function (factory, partial application) | Good | `Function.prototype.bind` |
| Callback needing setup-time context | Good, often the simplest option | Pass the context as an argument |
| Many instances with many methods | Each instance gets its own copy of every method | Class methods shared on the prototype |
| File-level privacy | Works, as an IIFE | ES module scope |
Closures cost a small amount of memory for each function object created. That cost is usually irrelevant. It matters when you create millions of instances, each with many methods.
Exercise
What does this code print, and why? function setup() { let x = 1; const read = () => x; x = 2; return read; } const r = setup(); console.log(r());
Show answer
It prints 2. The arrow function captures the binding x, not the value 1 it held when the arrow was created. By the time r() runs, x has been reassigned to 2, and the lookup reads the current value.
Exercise
Given const c1 = makeCounter(); const c2 = makeCounter(); using the makeCounter from this chapter, what do c1(), c1(), c2() return in that order? What would change if both variables were assigned from a single call, as in const c = makeCounter(); const c1 = c; const c2 = c;?
Show answer
The first version returns 1, 2, 1, because each makeCounter call creates its own environment with its own count. In the second version c1 and c2 are the same function, so they share one count, and the calls return 1, 2, 3.
Exercise
Write a function makeIdGenerator(prefix) that returns a function. Each call to the returned function should produce the next string in the sequence "prefix-1", "prefix-2", and so on. Separate generators must keep separate counts.
Show answer
function makeIdGenerator(prefix) { let n = 0; return () => ${prefix}-${++n}; } Each call to makeIdGenerator creates a new environment holding its own n and prefix, so generators do not affect each other.