Closures are created every time a function is defined inside another function. They're the mechanism behind private state, memoization and module patterns.
function makeCounter() {
let count = 0; // private — only accessible via the closure
return function increment() {
count += 1;
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2
// 'count' can't be accessed directly — only through counter()- Each call to makeCounter() creates a fresh, independent closure
- Used for private state, currying, memoization and event handler factories
- Watch out: closures inside loops can capture the wrong variable with var
Tip
Draw or describe the counter example — it's the single most common closures interview question.