A closure is a function that has access to variables from its outer scope, even after the outer function has returned.
A closure is created when a function is defined inside another function, and the inner function references variables from the outer function's scope. The inner function "closes over" these variables, maintaining access to them even after the outer function has finished executing.
Every function in JavaScript forms a closure. When a function is created, it retains a reference to its lexical environment—the scope in which it was defined. This includes all local variables that were in-scope at the time of the function's creation.
Common use cases include: data privacy (creating private variables that can't be accessed directly), factory functions that generate configured functions, callbacks that need access to outer scope variables, and maintaining state in functional programming patterns.
A classic example is a counter: function createCounter() { let count = 0; return { increment: () => ++count, get: () => count }; }. The returned object's methods have access to count even though createCounter has returned.
Be aware of closure-related gotchas: closures capture variables by reference, not value. In loops, this can lead to unexpected behavior where all closures reference the final value of a loop variable. Using let instead of var, or creating a new scope for each iteration, solves this issue.
A closure is a function that has access to variables from its outer scope, even after the outer function has returned.
Join our network of elite AI-native engineers.