Functions
Closures
Functions that remember the scope they were created in.
A closure is a function bundled together with references to its surrounding state — its lexical environment. The inner function keeps access to the outer function's variables even after the outer function has returned.
A closure is a backpack the function carries — it keeps the variables it needs zipped inside, wherever it travels.
Key concepts
1
Closures power data privacy (variables only reachable through the returned function), factory functions, and currying. They are also why a handler created in a loop can capture the wrong var value — a classic interview trap solved by using let.
data privacyfactory functionscurryingvarlet
2
The trade-off is memory: a closure keeps its captured variables alive, so holding many long-lived closures can prevent garbage collection.
javascript
function counter() {
let count = 0; // private state
return () => ++count; // closure over count
}
const next = counter();
next(); // 1
next(); // 2
// Loop trap: let fixes it, var does not
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // 0,1,2
}