Explain what a closure is in JavaScript.
You said:
The assistant said:
A closure is a function that keeps access to the variables of the scope where it was created, even after that scope has returned.
JavaScript
function counter() {
let count = 0;
return () => ++count;
}
const next = counter();
next(); // 1
next(); // 2Each call to counter() makes a new count, so two counters never share state.
You said:
When would I use one?
The assistant said:
Use a closure when a function needs private state:
- Counters and IDs that should not be global.
- Event handlers that remember their element.
- Factories that return configured functions.