Closures and Leaks
A closure keeps its lexical environment alive. If that environment holds a large object or a DOM node, and the function is still reachable (a listener, a timer, a cache), those values cannot be collected.
Detailed Explanation
Every function stores a link to the environment where it was created. That is how makeCounter works. The same link is how a 2 MB array you used once stays in memory for the life of a click handler.
The leak is not "closures are bad". The leak is a long-lived function + a fat environment. Typical shapes:
- An event listener added in
setup()that closes overdataand is neverremoveEventListener'd. setIntervalwithoutclearInterval.- A module-level
cachethat grows with every user id and never evicts. - A Promise that never settles, holding its executor's locals and every
.thenclosure. - A detached DOM node still referenced from a closure (see detached DOM).
Engines may optimise unused bindings out of an environment. You cannot rely on that. If huge is in the same scope as a small callback, treat huge as retained. Bind only what you need: const id = user.id; button.onclick = () => save(id) rather than closing over user if user holds a tree.
Debug with a heap snapshot: search for the constructor or a unique string, then read "retainers". The retainer path is usually Window → listener → function → context → your array.
Fix by shortening the function's life (removeEventListener, clearTimeout, AbortController on fetch plus dropping the promise), shrinking the environment (copy the scalar you need), or using WeakMap so metadata dies with the key.
What it costs you: heap growth over a long-lived tab or a long-lived Node process. A single SPA that never drops listeners on route change is the classic browser leak. A server cache keyed by raw request objects is the classic Node leak.
Reach for this checklist whenever you register a callback that might outlive the data it touched. Reach for WeakMap when the callback's lifetime should follow an object you do not own.
Code Examples
function attachLeaky(button, rows) {
// `rows` stays alive as long as the listener does
button.addEventListener("click", () => {
console.log(rows.length);
});
}
function attachTight(button, rows) {
const n = rows.length; // only the number is retained
const onClick = () => console.log(n);
button.addEventListener("click", onClick);
return () => button.removeEventListener("click", onClick);
}const cache = new Map();
function getUser(id, fetchUser) {
if (!cache.has(id)) cache.set(id, fetchUser(id));
return cache.get(id);
}
function evict(id) {
cache.delete(id);
}let timer = setInterval(() => {
// this closure and anything it touches live until clearInterval
}, 1000);
clearInterval(timer);
timer = null;Common Gotchas
`removeEventListener` needs the same function reference
an inline arrow you cannot name cannot be removed. Store the function.
Unused locals in the same scope may still be retained
do not put huge temporaries next to a long-lived callback.
A forgotten `setInterval` is a root
the host holds the callback. Clear it.
Module-level maps are immortal caches
they need a max size, a TTL, or `WeakMap` keys.