What is a closure?
Practice this questionDefinition:
A closure is a function together with access to the variables in the scope where it was created. That access remains available even after the outer function has finished running. Closures are useful for private state, callbacks and functions configured with some remembered value.
Key points:
-
A function keeps access to variables from where it was created.
-
Example: a counter function remembers its count between calls.
-
Closures can also keep large objects in memory longer than needed.
-
A closure keeps access to bindings, not a frozen snapshot; later changes to those bindings can be visible.
-
Each call to a function factory can create a separate set of remembered variables.
-
Long-lived callbacks can retain data through closures, so remove them when they are no longer needed.
Example:
function createCounter() {
let count = 0;
return function increment() {
count += 1;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2createCounterhas returned, butincrementstill has access to itscount.- Calling
createCounter()again creates a separate counter with its own state.
Interview point:
- Explain a counter or callback example and mention that remembering state can be useful but also retain memory.