JavaScript Closures
A closure is a function that remembers the variables from its outer (enclosing) scope, even after that outer function has finished executing.
Closures are the mechanism behind many powerful patterns, including private variables, memoization, and function factories.
How closures work
When a function is defined inside another function, it 'closes over' the variables of the outer function, keeping access to them even after the outer function returns.
Practical uses
Closures enable private state (data hidden from outside access) and function factories that generate customized functions.
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
let counter = makeCounter();
console.log(counter());
console.log(counter());1
2The returned function remembers and updates count even after makeCounter finished running.
function multiplier(factor) {
return num => num * factor;
}
let triple = multiplier(3);
console.log(triple(5));15triple 'remembers' factor=3 from when multiplier was called.
Key points
- A closure lets a function access its outer scope's variables later.
- Closures persist even after the outer function has returned.
- They enable private state and function factories.
- Every JavaScript function forms a closure over its defining scope.
