Sub topic 2
How Closures Keep Data Alive
This chapter assumes you know how closures and scope work, and that you have used timers and event listeners. It also builds on the earlier chapters: an object stays in memory as long as some path from a root can reach it.
Closures and Retained Scope
A closure keeps the variables it uses alive. As long as the function is reachable, everything it captured is reachable too.
function createHandler() {
const bigData = new Array(1_000_000).fill(0);
return function handler() {
return bigData.length;
};
}
const handler = createHandler();
// bigData stays in memory for as long as handler is reachable.When createHandler returns, its local scope does not go away. The handler function still refers to bigData, so the whole array stays in memory. A closure costs very little memory itself, but it can keep large data alive. If you only need bigData.length, compute that number outside the returned function and capture the number instead of the array.
Common Memory Leaks and How to Fix Them
A leak in JavaScript is memory that stays reachable after you stop needing it. The collector works correctly here. Your code is the thing still holding the reference.
| Leak pattern | What keeps it alive | Fix |
|---|---|---|
| Forgotten timer | The timer queue holds the callback | `clearInterval` / `clearTimeout` |
| Forgotten listener | The event target holds the handler | `removeEventListener` or an `AbortSignal` |
| Detached DOM node | A JS variable still points to a removed node | Set the reference to `null` |
| Unbounded cache | A `Map` or object that only grows | Evict entries, or use a `WeakMap` |
A running timer keeps its callback alive, along with everything the callback captures:
const intervalId = setInterval(() => {
console.log("polling");
}, 1000);
// When the work is no longer needed:
clearInterval(intervalId);For listeners, an AbortController lets one call remove the listener:
function onResize() {
console.log(window.innerWidth);
}
const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
// Later, when the component is torn down:
controller.abort(); // removes the listenerAssociating Data Without Leaking: WeakMap and WeakSet
A WeakMap holds its keys weakly. An entry does not keep its key object alive. Once nothing else references the key, the key and its value can both be collected.
const metadata = new WeakMap();
function tag(obj, info) {
metadata.set(obj, info);
}
let node = { id: 1 };
tag(node, { clicks: 0 });
node = null;
// The WeakMap does not keep the key alive, so the entry can be collected with it.A WeakSet does the same job for membership: it records "this object was seen" without keeping the object alive.
Exercise
A module caches computed layout data in a Map keyed by DOM elements. Memory grows as elements are added and removed. Why, and what is the simplest fix?
Show answer
The Map holds strong references to its keys, so removed elements stay reachable through the cache. Their data stays too. Replace the Map with a WeakMap, so an entry can be collected once its element is unreachable everywhere else.