/ˈkloʊʒər/
noun … “A function bundled with its environment.”
Closure is a programming concept in which a function retains access to variables from its lexical scope, even after that scope has exited. In other words, a closure “closes over” its surrounding environment, allowing the function to reference and modify those variables whenever it is invoked. Closures are widely used in Functional Programming, callbacks, and asynchronous operations.
Key characteristics of closures include:
- Lexical scoping: the function captures variables defined in its containing scope.
- Persistent state: variables captured by the closure persist across multiple calls.
- Encapsulation: closures can hide internal variables from the global scope, preventing accidental modification.
- First-class functions: closures are often treated as values, passed to other functions, or returned as results.
- Memory management: captured variables remain alive as long as the closure exists, which can impact garbage collection.
Workflow example: In JavaScript, a function can generate other functions that remember values from their creation context:
function makeCounter(initial) {
count = initial
return function() {
count += 1
return count
}
}
counter = makeCounter(10)
print(counter() ) -- Output: 11
print(counter() ) -- Output: 12Here, the inner function is a closure that retains access to the count variable, even after makeCounter has returned.
Conceptually, a closure is like a backpack carrying not only the function itself but also the variables it needs to operate. Wherever the function travels, it brings its environment along.
See Functional Programming, Higher-Order Function, Scope, Lexical Scoping.