Closures
A closure is a function plus the lexical environment it was created in. The function can read and write outer variables even after the outer function has returned.
Detailed Explanation
Every JavaScript function is a closure. When a function is created, it stores a reference to the environment that was current at that moment. Later, when it looks up a name that is not a local or a parameter, it follows that stored link. The outer function does not have to still be running. The environment stays alive as long as any function that points at it is reachable.
The useful case is a function returned from another function:
function makeCounter() {
let n = 0;
return function next() {
n += 1;
return n;
};
}
next closes over n. Each call to makeCounter creates a new environment and a new n. Two counters do not share state. That is the standard way to hide mutable data without a class: the variable is not on an object, and nothing outside makeCounter can touch it except by calling next.
Closures capture bindings, not snapshots. If the outer variable changes after the inner function is created, the inner function sees the new value. A loop that creates callbacks with var i gives every callback the same binding, which ends at the final i. A loop with let i gives each iteration its own binding, so each callback sees its own i.
Common places you already use closures: event handlers that read a name from the surrounding render function, promise .then callbacks that use an id from the caller, partial application (const addTax = (rate) => (amount) => amount * (1 + rate)), and module-level caches.
The cost is lifetime. A closure keeps its environment reachable. If that environment holds a large array, a DOM node, or a socket, those stay in memory until the function itself is dropped. A handler you add with addEventListener and never remove is a closure that pins whatever it closed over. See also detached DOM nodes and accidental listeners.
Reach for a closure when a function needs private state or needs values from the place it was created. Reach for an object or a class when that state has several operations and a name of its own. Do not "avoid closures"; you cannot write JavaScript without them. Do avoid closing over more than you need, and do not keep a function alive longer than its job.
Code Examples
function withPrefix(prefix) {
return function label(id) {
return `${prefix}:${id}`;
};
}
const userKey = withPrefix("user");
const orderKey = withPrefix("order");
console.log(userKey(7)); // => user:7
console.log(orderKey(7)); // => order:7function makeAccount(opening) {
let balance = opening; // private to this environment
return {
deposit(amount) {
balance += amount;
return balance;
},
read() {
return balance;
},
};
}
const acct = makeAccount(10);
console.log(acct.deposit(5)); // => 15
console.log(acct.read()); // => 15const delayed = [];
for (var i = 0; i < 3; i++) {
delayed.push(() => i);
}
console.log(delayed.map((fn) => fn())); // => [ 3, 3, 3 ]
const delayedLet = [];
for (let j = 0; j < 3; j++) {
delayedLet.push(() => j);
}
console.log(delayedLet.map((fn) => fn())); // => [ 0, 1, 2 ]Common Gotchas
Closures see live bindings
they do not copy the value at creation time. If you need a snapshot, assign `const snapshot = value` in the inner scope or pass `value` as an argument.
`var` in a loop is one binding
every callback created in that loop shares it. Use `let` or bind the value per iteration.
A long-lived closure pins memory
an event listener, a timer, or a cached callback keeps its outer variables (and anything those point at) alive.
Every function closes over its scope
even if it never reads an outer name, the link exists. The interesting closures are the ones that use that link.