Scope at creation time
JavaScript uses lexical scope, meaning where a function is written decides which variables it can see. A closure is the bundle of a function plus the variable environment it captured when it was defined.
- Inner functions read and write the outer variables they reference.
- Those variables stay alive as long as the closure does.
- Each call to an outer function creates a fresh environment.
Why closures matter
Closures let you build private state without classes. The captured variables cannot be touched from outside, only through the functions you return.
- A counter can hold a private count that only its methods change.
- Event handlers remember the data they were set up with.
- A common bug is capturing a loop variable that changes before the callback runs.
Using let in a loop creates a new binding each iteration, which fixes the classic closure in a loop trap that var causes. Closures are not magic, just scope that outlives the call that made it.
Key idea
A closure captures variables by reference from where it was defined, keeping that environment alive after the outer call returns.