Loading lessons...
Closures
Closures
A closure is a function that remembers the variables from the scope where it was created, even after that scope is gone.
The classic example
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2
counter(); // 3
What is happening?
makeCountercreates a local variablecount.- It returns an inner function.
- The inner function "closes over"
countand keeps it alive. - Each call to
counter()can still access and updatecount.
Why closures matter
- Create private variables that other code cannot touch.
- Build functions that remember state.
- Used everywhere: counters, event handlers, and module patterns.
Private variables
The variable count is not accessible from outside, only through the closure:
counter.count; // undefined
TL;DR
- A closure is a function plus its remembered scope.
- Inner functions keep access to outer variables.
- Closures create private state.
- Great for counters and encapsulating data.