Sub topic 6
What a Closure Is
This chapter assumes you can declare and call functions, return a function from another function, and follow how the scope chain looks up a variable. Earlier chapters covered lexical scope and lexical environments. This one puts those pieces together.
The Definition
A closure is a function together with the lexical environment in which it was created. Every JavaScript function keeps a hidden reference to the environment that was active when the function was defined. When the function runs later, variable lookup starts in the function's own scope and then follows that saved reference outward.
This means a function can still read and update the variables of an outer function after the outer function has returned.
A Worked Example
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
const other = makeCounter();
console.log(other()); // 1Here is what happens, step by step:
- Calling
makeCounter()creates a new lexical environment that holdscount = 0. - The inner function is created inside that environment, so it stores a reference to it.
makeCounterreturns. Its execution context leaves the call stack, but the environment holdingcountstays alive because the returned function still references it.- Each call to
counter()findscountthrough that saved reference and increments it. - Calling
makeCounter()again creates a second, separate environment.othercloses over a differentcount, so the two counters do not affect each other.
When a Closure Is Created
A closure is created every time a function is created, not when the function is called. Every function in JavaScript is technically a closure over its surrounding environment. The term usually refers to the interesting case: a function that outlives the scope it was defined in, by being returned, stored, or passed as a callback.
What Gets Captured
A closure keeps the whole environment it can reach. Two points matter in practice:
- It holds a link to the variables themselves, not copies of their values. A later chapter explores what this means.
- Only the variables the function can reach through the scope chain are available. Variables local to unrelated functions are not.
| Situation | Does the inner function see the variable? |
|---|---|
| Variable declared in an enclosing function | Yes |
| Variable declared in the global scope | Yes |
| Variable declared inside a sibling function | No |
| Variable declared in the caller's scope | No, unless the caller also encloses it |
Common Errors
- Assuming a returned function loses access to outer variables once the outer function finishes. The environment stays alive as long as something references it.
- Expecting two calls to a factory like
makeCounterto share state. Each call creates a fresh environment. - Thinking closures need special syntax. Any nested function that refers to an outer variable is using one.
Exercise
What does this code log, and why? function make() { let n = 10; return () => n--; } const a = make(); const b = make(); a(); a(); console.log(a(), b());
Show answer
It logs 8 10. Each call to make creates its own environment with n = 10. The two earlier calls to a return 10 and 9 and leave n at 8, so the third call returns 8 (post-decrement) and leaves n at 7. Then b returns 10 from its own separate n.
Exercise
When is the closure for the inner function in makeCounter created: when makeCounter is called, or when counter() is called?
Show answer
When makeCounter is called, because that is when the inner function is created and it records its surrounding environment at that moment. Calling counter() only uses the environment it already holds.