Closures
A closure is a function together with access to its surrounding lexical environment. It can retain access to bindings after the outer call returns.
The remembered binding can keep changing; a closure is not a frozen photograph of its first value.
See the mechanism
0Follow one example
The first two calls use the same retained count binding, producing 1 then 2. Calling makeCounter again creates an independent binding starting at 0, so its first increment produces 1. The outer invocation returns, but the returned function still has access to the binding it uses.
Predict, change and check
Predict: If you call makeCounter inside every iteration, will one counter keep increasing?
Test your explanation: Create two counters and alternate their calls. Write a separate count box for each outer invocation to explain why neither changes the other.
The tasks below ask you to explain that result and apply the idea to different inputs.
Apply and distinguish
A closure retains bindings, not frozen screenshots
A closure is a function together with access to its lexical environment. A later call can observe a retained binding's updated value. Creating two independent counter factories can create two independent environments; calling the same returned counter twice reuses one environment.
Captured values can retain large objects or detached DOM nodes through an ownership path. A closure is useful, not automatically a leak; the question is whether something keeps it reachable longer than intended. Test separate instances and shared instances, then explicitly release owners during component cleanup.
Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.