Functions, Scope & Object Model
Lexical Scope & Closures
JavaScript uses lexical scope: where a function is written determines which variables it can access. A closure is a function retaining access to variables from its outer lexical environment even after that outer function has returned.
- Scope is based on code location, not caller
- A closure captures variables, not snapshots
- Closures are ordinary, not exotic
- Closures can be a clean encapsulation tool
- Closures can retain memory
function createCounter() {
let count = 0
return {
next() {
count += 1
return count
},
reset() {
count = 0
},
}
}
const counter = createCounter()
counter.next() // 1
counter.next() // 2| Use | Example | Watch out |
|---|---|---|
| Encapsulation | Factory with private state | Hidden state can still become hard to test |
| Callbacks | Event handler reads outer variable | Stale values in long-lived callbacks |
| Memoization | Cache closed over by function | Unbounded memory growth |
| Configuration | Function factory | Too many layers can obscure flow |