liveBook · Manning

Closure

As explained in Acing the Frontend Interview

A closure is a function together with the lexical environment whose variables it can access after that environment's enclosing execution has ended.

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

How Acing the Frontend Interview covers it

How deep it goes
Traces lexical persistence through code and extends into closure bugs, memory leaks, and interval cleanup.
Examples
Uses a persistent counter, event handlers retaining large objects, and a React useInterval timer.
What it assumes
Assumes JavaScript functions and execution contexts while reinforcing lexical scoping, scope chains, and variable persistence.
What you can do after
Diagnose/debug scope resolution, stale callback behavior, retained state, and event-handler memory risks.
How it connects
Connects closures with lexical scoping, scope chains, higher-order functions, private variables, React Hooks, and memory management.

Also explained in

Compare how 24 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Acing the Frontend Interview. The section links point to the parts of the book it draws on.