Closures and private function state
A closure is a function that keeps access to variables from the place it was created.
How it works
Imagine each call to makeCounter writing its count on a separate sheet. The returned function keeps its own sheet. When you call a twice and b once, a’s sheet reaches 2 while b’s reaches 1. The factory can return without losing either sheet.
Walk through an example
A counter factory can create count = 0 and return a function that increments it. The returned function still sees that count after the factory returns.
What to watch for
Closures retain access to bindings, including their updates. Two calls to the factory produce two separate counters, each with its own binding.
Code example
function makeCounter() {
let count = 0;
return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
console.log(a(), a(), b());Check your understanding
What does b return on its first call?
See the example and explanation
- Worked example
- Given
Create counters a and b. Call a twice and then b once. - Answer
1
Each factory call creates a fresh count of 0. Calling a never changes the separate count inside b.