How it works
The explanation, with examples you can run.
Reachable means alive
The collector doesn't count how often something is used; it asks whether it can still be reached. Common ways memory stays reachable by accident:
- an event listener on a long-lived element (or
window) that closes over a big object, never removed; - a
Mapused as a cache with no limit or expiry; - a
setIntervalthat is never cleared, together with everything its callback uses; - detached DOM nodes still referenced from JavaScript.
Weak references
WeakMap and WeakSet hold their keys weakly: an entry doesn't keep its key alive. They are the right tool for attaching extra data to objects you don't own.
Press Run to see what your code prints, in order.
Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.
WeakRef and FinalizationRegistry exist too, but when (or whether) the collector runs is up to the engine, so don't build program logic on them.
Finding a leak
Take two heap snapshots in DevTools (Memory panel) a few actions apart and compare what grew. In Node, start with node --inspect and use the same tools; process.memoryUsage() gives a quick number, and --max-old-space-size changes how large the old generation may grow.
Check yourself
2 questions. Get them all right to finish this topic.
0 of 2 right so far. Get all two to finish this topic.