JavaScript · Question 33
What is a closure in JavaScript, and why can an inner function access variables after the outer function returns?
Direct answer
A closure is a function together with access to the lexical environment in which it was created, so referenced outer bindings can remain reachable even after the outer function has finished executing.
A closure is not simply “a function inside another function.” The important idea is lexical scope combined with function creation. When a function is created, its scope is determined by where that function appears in source code, not by where it is later called.
For example, function makeCounter(){ let count = 0; return () => ++count; } returns a function that still refers to the count binding. Calling the returned function later can continue updating that same binding even though makeCounter() has already returned.
- Encapsulation — keep state private behind returned functions.
- Function factories — create callbacks configured with different captured values.
- Async/event handlers — callbacks can retain request IDs, configuration, or local state needed later.
- Memoization and caching — a returned function can retain a cache without exposing it globally.