Sub topic 3
Closures: Functions That Remember
This chapter assumes you are comfortable with JavaScript functions and arrow functions, know the difference between let, const, and var, and understand that a variable declared inside a function cannot be seen outside it. The previous chapter showed that functions are values: you can return them, store them, and pass them around. Closures explain what a returned function can still reach after the function that created it has finished.
The Working Model
A closure is a function together with the variables from the scope where it was defined. JavaScript uses lexical scope, which means a function's access to variables is decided by where the function appears in the source code. Where it is later called does not matter.
When a function is created, it keeps a hidden reference to its surrounding scope. If that function outlives its parent, for example because the parent returned it, the surrounding variables stay alive for as long as the function can still use them.
function makeCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
const other = makeCounter();
console.log(other()); // 1 (separate closed-over state)Each call to makeCounter creates a new scope with its own count. The arrow function returned from that call closes over that particular count. next and other never share state, because each one was created by a separate call.
Closures Capture Bindings, Not Values
A common misunderstanding is that a closure copies a variable's value at the moment the function is created. It does not. It keeps a live reference to the variable binding, so it sees later changes.
let greeting = 'Hello';
const greet = (name) => `${greeting}, ${name}`;
console.log(greet('Ada')); // Hello, Ada
greeting = 'Hi';
console.log(greet('Ada')); // Hi, AdaThis is exactly why makeCounter works: the inner function updates the same count on every call. It also means a function that closes over a variable someone can reassign is not pure. Its output depends on state outside its arguments. Closing over const bindings that hold primitive values or frozen objects avoids that problem.
The Loop Gotcha: `var` vs `let`
The difference between capturing bindings and capturing values shows up most clearly in loops.
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map((f) => f())); // [ 3, 3, 3 ]
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map((f) => f())); // [ 0, 1, 2 ]var is function-scoped, so the whole loop shares one i binding. All three closures point to it, and by the time they run, the loop has left i at 3. let in a for header creates a fresh binding on every iteration, so each closure captures its own j. The same bug appears with setTimeout callbacks and event handlers created inside a var loop. Using let, or calling forEach with a callback, fixes it.
Configuring Behavior with Closures
In functional code, closures are mostly used to fix configuration in place, not to hold changing state. A factory takes some settings and returns a specialized function that remembers them.
const makeMultiplier = (factor) => (n) => n * factor;
const makeFormatter = (currency) => {
const fmt = new Intl.NumberFormat('en-US', { style: 'currency', currency });
return (amount) => fmt.format(amount);
};
const triple = makeMultiplier(3);
const usd = makeFormatter('USD');
console.log([1, 2, 3].map(triple)); // [ 3, 6, 9 ]
console.log(usd(1234.5)); // $1,234.50triple and usd are pure. They depend only on their argument and on values that never change after creation. makeFormatter also shows a performance benefit: the costly Intl.NumberFormat object is built once and reused on every call. This pattern of locking in arguments in advance is what the later chapters on currying, partial application, and memoization build on.
Private State and Encapsulation
JavaScript has #private class fields now, but closures were the original way to hide data, and they still work well. Variables in the factory's scope can only be reached through the functions it returns.
function createAccount(initial) {
let balance = initial;
const history = [];
return Object.freeze({
deposit(amount) {
if (amount <= 0) throw new RangeError('amount must be positive');
balance += amount;
history.push({ type: 'deposit', amount });
return balance;
},
balance: () => balance,
history: () => history.map((entry) => ({ ...entry }))
});
}
const acct = createAccount(100);
acct.deposit(50);
console.log(acct.balance()); // 150
console.log(acct.history()); // [ { type: 'deposit', amount: 50 } ]
console.log(acct.balance = 0); // ignored: object is frozen
console.log(acct.balance()); // 150The history accessor returns copies, so callers cannot change the internal array. Without those copies, the privacy would leak, because a closure that hands out a reference to mutable internal data also hands out the ability to change it. This module is stateful by design. Closures can wrap impure state as easily as pure configuration, so it is your job to know which one a given closure holds.
Failure Modes
| Problem | Cause | Fix |
|---|---|---|
| Every callback sees the last loop value | `var` shares one binding across iterations | Use `let` or `forEach` |
| Function returns different results over time | Closed-over variable is reassigned or mutated | Close over constants. Make any intended state explicit |
| "Private" data changed from outside | Accessor returns a reference to internal object or array | Return copies or frozen values |
| Memory not released | A long-lived closure keeps a large object reachable | Copy out only what you need, and remove listeners and timers |
| Stale value in a callback | Closure captured an older binding, for example from a previous render or call | Read from the current source or recreate the callback |
Memory Retention in Detail
A closure keeps alive everything it references. Engines such as V8 only retain variables that some inner function actually uses. However, all closures created in the same scope share one context object. If one inner function references a large array, that array stays alive for as long as any sibling closure from the same scope is alive, even a sibling that never touches the array.
function setup() {
const bigData = new Array(1e6).fill('x');
const size = bigData.length; // extract what is needed
return () => size; // bigData is not referenced, so it can be collected
}
const getSize = setup();
console.log(getSize()); // 1000000Event listeners and setInterval callbacks are the usual sources of leaks. They stay registered, so everything they close over stays reachable. Remove them when you are done with them.
Exercise
Write a function once(fn) that returns a new function. The first call runs fn with the given arguments and returns its result. Every later call returns that same first result without running fn again.
Show answer
Use a closure to remember whether fn has run and what it returned:
const once = (fn) => { let done = false; let result; return (...args) => { if (!done) { done = true; result = fn(...args); } return result; }; };
const init = once(() => { console.log('running'); return 42; });
init(); init(); // logs 'running' once, and both calls return 42
Exercise
What does this code log, and why? let rate = 2; const scale = (n) => n * rate; rate = 10; console.log(scale(3));
Show answer
It logs 30. The closure captures the binding rate, not the value it held when scale was created. By the time scale(3) runs, rate has been reassigned to 10. This also makes scale impure. Declaring const rate = 2 would make it pure.
Exercise
A loop for (var k = 0; k < 3; k++) setTimeout(() => console.log(k), 0); prints 3 three times. Give two different fixes that make it print 0, 1, 2.
Show answer
First, change var to let, so each iteration gets its own binding. Second, capture the value in a new scope for each iteration, for example [0, 1, 2].forEach((k) => setTimeout(() => console.log(k), 0)); or an immediately invoked function ((k) => setTimeout(() => console.log(k), 0))(k) inside the loop body.