Holding On, and Letting Go
A leak in JavaScript is not forgotten memory; it is memory something is still deliberately pointing at.
Garbage collection frees what is unreachable. A leak means a reference survives that you no longer want: a listener, a timer, a closure, a cache. WeakMap and WeakSet hold references that do not count, which makes them the right tool for metadata about objects you do not own.
EXERCISE
1Reachability, and the Four Common Leaks
The collector frees anything nothing can reach, so a leak is always something still reaching.
has no free. The garbage collector removes any object that cannot be reached from a root, such as a global, a variable on the stack, or something one of those points at.
So a leak is never "memory that was forgotten". It is always a reference you no longer want but still have. That reframing makes leaks findable, because you can go looking for the reference.
Leak one: a listener on an element that is gone.
function setUp(element, data) {
element.addEventListener("click", () => {
console.log(data.value);
});
}
Removing element from the page does not free it. The listener holds the closure, the closure holds data, and the browser holds the listener. Keep the removal function and call it:
function setUp(element, data) {
const handler = () => console.log(data.value);
element.addEventListener("click", handler);
return () => element.removeEventListener("click", handler);
}
Leak two: a timer nobody cleared.
setInterval(() => {
updateWidget(widget);
}, 1000);
The interval keeps running and keeps widget alive forever. This was Unit 4's point, and it is a leak as well as a correctness bug. Hold the id and clear it.
Leak three: a cache with no limit.
const cache = new Map();
function getUser(id) {
if (!cache.has(id)) {
cache.set(id, expensiveLookup(id));
}
return cache.get(id);
}
Correct, fast, and it grows until the process runs out. Every cache needs a bound: a maximum size, a time limit, or weak keys.
Leak four: a closure that captures more than it needs.
function makeHandler() {
const hugeArray = new Array(1e6).fill("data");
const summary = hugeArray.length;
return function () {
console.log(summary); // only needs the number
};
}
Engines usually optimise this, and they cannot always tell, particularly if eval or a debugger is involved. Pulling out what you need before creating the closure is free insurance:
function makeHandler() {
const summary = new Array(1e6).fill("data").length;
return function () {
console.log(summary);
};
}
Finding one:
// Take a heap snapshot in DevTools, perform the action several
// times, take another, and compare. A detached DOM node or a
// growing array in the diff is the reference you are looking for.
Any function that attaches, subscribes or schedules should return the way to undo it. That single habit prevents all of the first two categories, and it is why useEffect in is designed around a returned cleanup function rather than around a separate teardown hook.
EXERCISE
2WeakMap, WeakSet and References That Do Not Count
A weak reference lets you attach data to an object without keeping that object alive.
The problem a Map has:
const metadata = new Map();
function track(element) {
metadata.set(element, { clicks: 0 });
}
The map now holds a strong reference to every element passed to it. Remove those elements from the page and they cannot be collected, because the map is still pointing at them. The map itself never shrinks.
WeakMap holds keys weakly:
const metadata = new WeakMap();
function track(element) {
metadata.set(element, { clicks: 0 });
}
// When the element becomes unreachable everywhere else, both the
// element and its entry are collected. Nothing needs cleaning up.
The reference from a WeakMap does not count towards reachability. That is the entire feature, and it makes a whole class of manual bookkeeping unnecessary.
What you give up:
const wm = new WeakMap();
// wm.size; undefined
// for (const k of wm) { } not iterable
// wm.keys(); not a method
No size, no iteration, no clearing. This is not an oversight. If you could list the keys, the collector's timing would become observable from your program, and whether a key appeared would depend on when a collection happened to run.
Keys must be objects:
const wm = new WeakMap();
wm.set({}, "fine");
// wm.set("a string", "no");
// TypeError: Invalid value used as weak map key
Primitives cannot be weakly held, because there is nothing to collect.
The three uses that come up in practice:
// 1. Metadata about objects you do not own
const lastSeen = new WeakMap();
function markSeen(user) {
lastSeen.set(user, Date.now());
}
// 2. Truly private data, an alternative to # fields
const internals = new WeakMap();
class Account {
constructor(balance) {
internals.set(this, { balance });
}
get balance() {
return internals.get(this).balance;
}
}
// 3. Memoising by object identity
const results = new WeakMap();
function analyse(config) {
if (!results.has(config)) {
results.set(config, expensive(config));
}
return results.get(config);
}
That third one is the memoisation from the next unit, and it is why WeakMap belongs here rather than in a unit of its own: keyed by an object is the most common reason to reach for it, and doing it with a Map is a leak by construction.
WeakSet is the same idea with no value:
const processed = new WeakSet();
function handle(item) {
if (processed.has(item)) return;
processed.add(item);
doWork(item);
}
"Have I already seen this object?" without keeping it alive.
Pro Tip: Reach for
WeakMapwhenever the key is an object whose lifetime you do not control, such as a DOM node, a user object from elsewhere, or a request. If you find yourself writing code to delete entries when objects go away, aWeakMapremoves that code and the bug that comes with forgetting it.
EXERCISE
3WeakRef and FinalizationRegistry
Two newer tools let you observe collection directly, and the specification itself advises against relying on them.
WeakMap holds keys weakly but gives you no visibility. Two additions go further, and both come with unusually blunt warnings attached.
WeakRef holds a single object weakly:
const ref = new WeakRef(someLargeObject);
// Later:
const obj = ref.deref();
if (obj) {
use(obj);
} else {
// it was collected; rebuild or give up
}
deref returns the object if it is still alive and undefined if it has been collected. The value can disappear between two calls, so you must check every time.
A plausible use, an image cache that can be reclaimed:
const cache = new Map();
function getThumbnail(url) {
const cached = cache.get(url)?.deref();
if (cached) {
return cached;
}
const image = renderThumbnail(url);
cache.set(url, new WeakRef(image));
return image;
}
The cache never prevents collection, so memory pressure reclaims thumbnails rather than the tab crashing. Note the Map still grows with dead WeakRef objects, which is what the next tool is for.
FinalizationRegistry runs a callback after collection:
const registry = new FinalizationRegistry((url) => {
cache.delete(url); // clean up the dead entry
});
function getThumbnail(url) {
const cached = cache.get(url)?.deref();
if (cached) return cached;
const image = renderThumbnail(url);
cache.set(url, new WeakRef(image));
registry.register(image, url);
return image;
}
The callback receives the token you registered, not the object, because handing you the object would resurrect it.
Now the warnings, which are genuine:
// The callback may never run. Collection is not guaranteed at all.
// It may run much later than you expect.
// It will not run if the page closes or the process exits.
// Timing differs between engines and between versions.
MDN and the specification both say to avoid these where possible. They are correct. Anything important must not depend on a finaliser: closing a file, releasing a lock, flushing a buffer. Use explicit cleanup, which is the try/finally from lesson 1.
What they are actually for:
// Reclaimable caches, where losing an entry is harmless.
// Detecting leaks in development, by logging what never gets collected.
// Cleaning up bookkeeping that mirrors objects you do not own.
That third one is the honest use. Everything else is better served by explicit lifetimes, and reaching for a finaliser is usually a sign that ownership was never decided.
Pro Tip: If you find yourself wanting
FinalizationRegistry, first ask who owns the object and when they are done with it. Almost always that question has an answer, and the answer is aclose, adisposeor a returned cleanup function. A finaliser is what you use when genuinely nobody can know, which is rarer than it feels.
