Functions

Closures

Functions that remember the scope they were created in.

intermediate All levels

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.