liveBook · Manning

Closure

As explained in Secrets of the JavaScript Ninja, Third Edition

A closure is a function together with access to variables from its surrounding lexical environment.

A closure lets a function access variables and other functions that were in scope when it was defined. The function carries access to that original scope, even if the scope that created it has finished executing. section 7.1

This is why a function can still read variables from its defining scope after it is reassigned and called elsewhere. The captured variables remain available as long as a reference to the function exists. section 7.1

Closures are useful when a function needs to retain or access surrounding state:

  • A memoized function can keep a private cache between calls. section 7.2.1
  • A callback can read surrounding variables when it runs later, as in a timer animation. section 7.2.2
function memoize(func) {
  const cache = new Map();
  return (arg) => {
    if (!cache.has(arg)) {
      cache.set(arg, func(arg));
    }
    return cache.get(arg);
  };
}
 
// Memoize functions with expensive computations:
const memoizedIsPrime = memoize(isPrime);

The returned function reuses the cache created by memoize; that cache stays available while the function is referenced. section 7.2.1

Listing 7.3 Using a closure in a timer interval callback
let tick = 0;
const timerId = setInterval(() => { #A
  tick++;
  console.log(`tick ${tick}`);
  if (tick === 5) { #B
    clearInterval(timerId); #B
  } #B
}, 10);

The timer callback reads and updates tick, then uses timerId to stop the interval. section 7.2.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains captured lexical variables and surviving scopes through examples, then links closures to broader JavaScript scoping rules.
Examples
Uses nested functions, a memoization cache, and a timer callback that counts ticks and clears its interval.
What it assumes
Assumes familiarity with JavaScript functions and callbacks while explaining scope and variable visibility.
What you can do after
Apply closures to preserve a memoization cache or let a delayed callback access surrounding state.
How it connects
Connects closures to lexical scope, callbacks, memoization, and function-scoped privacy.

Also explained in

Compare how 24 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.