JavaScript closures, clearly explained
A closure is a function together with access to lexical variables from the scope where it was created, even after that outer function returns.
How it works
Each call to makeCounter creates a separate count binding, so calling the returned function twice produces 1 and then 2, while another counter starts at 1; this is useful when a callback needs to keep access to state without placing that state in a global variable.
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2Read the documentationCommon misconception
Closures retain access to bindings; they do not freeze a copy of every value.
Quick practice
1. Can a closure outlive its outer call?
Yes.
2. Are closures only for private state?
No.
3. What scope do they capture?
The lexical scope where the function was created.