A closure is a function bundled together with the variables from the scope in which it was created. The function “closes over” those variables, keeping access to them even after the code that created them has finished running. Mozilla’s JavaScript documentation defines it as “the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment),” adding that “a closure gives a function access to its outer scope.”
The mechanism depends on lexical scoping: an inner function can read the variables of the function that encloses it. When that inner function is returned or otherwise carried away, it retains a live reference to those outer variables rather than a frozen copy. As the MDN documentation notes, “in JavaScript, closures are created every time a function is created, at function creation time.”
This is what lets a function remember an environment after the outer function has returned. A function that builds and returns another function can capture local values, and the returned function will continue to see them on every later call. The captured variables persist for as long as the closure that uses them is reachable.
Closures are the basis of many common patterns. Callbacks rely on capturing the surrounding context so they can run later with the right data. Currying and partial application use closures to remember already-supplied arguments. And closures provide a way to give a function private, persistent state, since the captured variables are visible only through the closure itself.