Sub topic 11
Closures: Functions That Remember Their Scope
This chapter assumes you know how the scope chain resolves names, and that you understand function scope and block scope with let and const. You should also be able to run code in Node.js or a browser console.
The Working Model
A closure is a function together with the scope it was created in. In JavaScript every function is a closure. When a function is created, it keeps a reference to its surrounding scope. This works because of lexical scope: a function looks up names where it was written, not where it is called.
You only notice this when a function outlives the scope that created it. Normally a function's local variables become unreachable once the function returns. If an inner function that refers to those variables is still reachable, though, the variables stay alive.
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2makeCounter has already returned by the time next() runs. The returned function still reaches count through its scope chain, because its outer scope is the scope of that call to makeCounter.
Closures Capture Variables, Not Values
A closure does not copy values when it is created. It holds a live reference to the variable binding. If the variable changes later, the closure sees the new value.
function makeGreeter() {
let name = "Ada";
const greet = () => `Hello, ${name}`;
name = "Grace";
return greet;
}
console.log(makeGreeter()()); // "Hello, Grace"greet was created while name was "Ada", but it reads name when it runs, and by then the value is "Grace". This rule explains most surprising closure output, including the loop bug covered in the next chapter.
Each Call Creates a Fresh Scope
Each call to the outer function creates a new scope with its own variables. Closures created by separate calls share nothing.
function makeCounter() {
let count = 0;
return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
console.log(a(), a(), b()); // 1 2 1Closures created in the same call do share variables. This lets you build private state that is reached only through a fixed set of functions:
function createAccount(initial) {
let balance = initial;
return {
deposit(amount) {
balance += amount;
return balance;
},
getBalance() {
return balance;
},
};
}
const acct = createAccount(100);
acct.deposit(50);
console.log(acct.getBalance()); // 150
console.log(acct.balance); // undefinedCode outside createAccount has no name it can use to reach balance. Only the two methods can.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Expecting a snapshot of a value | The closure shows the latest value | Copy the value into a new `const` at the moment you want to keep it |
| Sharing one outer variable between callbacks by accident | Every callback reads the same binding | Give each callback its own scope (a function call or a `let` block) |
| Keeping large objects reachable | Memory is not freed while the closure lives | Drop references to the closure, or avoid capturing big data you don't need |
Exercise
What does this code log, and why? function f() { let x = 1; const g = () => x; x = 2; return g; } console.log(f()());
Show answer
It logs 2. The closure g captures the variable x itself, not its value at creation time. By the time g runs, x has been reassigned to 2.
Exercise
Two counters are created with const c1 = makeCounter(); const c2 = makeCounter(); using the makeCounter from this chapter. After calling c1() three times, what does c2() return?
Show answer
It returns 1. Each call to makeCounter creates a new scope with its own count variable, so c1 and c2 do not share state.