JavaScript Closures: Capture and Lifetime
Quick answer
A closure is a function together with access to the lexical environment in which it was created. That access can outlive the creating call.
How it works
Returning an inner function does not copy every outer value. The function can observe updates to captured bindings. Multiple closures created in one invocation can share bindings; separate invocations normally establish separate local environments. Reachable closures can keep referenced state reachable; garbage collection timing is not guaranteed.
function make() { let n = 1; const read = () => n; n = 4; return read; }console.log(make()());Expected output in Node.js:
4The closure reads the updated binding.
function pair() { let n = 0; return {add: () => ++n, read: () => n}; }const p = pair(); p.add(); p.add(); console.log(p.read());Expected output in Node.js:
2Both methods access one binding in the same invocation.
Common mistakes
Capture is not a frozen snapshot; distinguish a binding from the value it currently holds.
Practice
Predict the result if the two methods in pair come from separate calls.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Closures: Capture and Lifetime — Knowledge Check
Apply the taught concept and predict the output.
What does a closure retain access to?
When can a closure observe a changed outer binding?
What can keep captured state reachable?
What is the exact console output in JavaScript Closures: Capture and Lifetime example 1?
function make() { let n = 1; const read = () => n; n = 4; return read; }console.log(make()());What is the exact console output in JavaScript Closures: Capture and Lifetime example 2?
function pair() { let n = 0; return {add: () => ++n, read: () => n}; }const p = pair(); p.add(); p.add(); console.log(p.read());