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























