A closure in JavaScript is a function that remembers the variables from its outer lexical scope even after the outer function has finished executing.
In other words:
- A closure gives a function access to an outer function’s variables, even after the outer function has executed.
- The function “closes over” the variables from its outer scope.
Key Characteristics of Closures:
- Closures remember the environment in which they were created.
- Closures can access variables from their outer scope even after the outer function is done executing.
- Closures are created every time a function is created inside another function.
Example 1: Basic Closure Example
javascriptCopyEditfunction outer() {
let count = 0; // Variable in outer scope
function inner() {
count++; // Accessing outer scope variable
console.log(count);
}
return inner;
}
const counter = outer(); // outer() is executed, but its scope is preserved
counter(); // 1
counter(); // 2
counter(); // 3
Explanation:
outer()
creates the variablecount
.inner()
is defined insideouter()
and has access tocount
.- Even though
outer()
is done executing, thecounter
function still rememberscount
because of closure. - Each time
counter()
is called, it remembers the previous state ofcount
.
Example 2: Closure with Parameters
javascriptCopyEditfunction multiplier(factor) {
return function (number) {
return number * factor;
};
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
Explanation:
multiplier()
returns a function that multiplies byfactor
.- The returned function remembers
factor
due to closure, even aftermultiplier()
has finished execution.
Why Are Closures Useful?
- Data privacy: Variables in closures are not accessible from outside.
- Stateful functions: Functions can remember state between calls.
- Callbacks and Event Handlers: Closures are common in asynchronous programming and event handling.
Common Use Cases of Closures:
Use Case | Example |
---|---|
Data hiding/encapsulation | Counter, private variables |
Factory functions | Generating customized functions |
Callbacks and async functions | Event listeners, setTimeout |
Function currying | Partial application of functions |
Key Takeaways:
- A closure is a function + the environment in which it was created.
- Closures allow functions to remember and access their outer scope variables even after the outer function has completed.
- Used heavily in JavaScript patterns like module pattern, callbacks, and functional programming.