A closure combines a function with the lexical environment containing the variables it can access after the enclosing execution has ended. Interviewers use closures to assess scope tracing, runtime reasoning, and debugging. section 3.1
Persistent state through a returned function
The outer function initializes count and returns inner. Although outer has finished, inner retains access to count. Calling counter repeatedly produces 1, 2, and 3 because the same closed-over variable persists between calls. section 3.1
Use closures to reason about:
- Lexical scoping and the scope chain: determine which variable binding a function resolves. section 3.1
- Encapsulated state: retain private mutable data without exposing it directly. section 3.1 section 3.5
- Memory risks: inspect handlers that retain large objects and clear data or remove listeners during cleanup. section 3.1
Closures in a React timer
The useInterval hook closes over tick and savedCallback while separating callback updates from interval setup. The saved callback keeps interval execution aligned with the latest state or props, and cleanup clears the interval. The Timer component then uses functional state updates to increment seconds. section 3.5
Listing 3.2 Closure—tracing the scope chain and persistence
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Trace the retained count variable through outer, inner, and successive counter calls. section 3.1























