JavaScript path · Under the hood · Topic 9 of 12

Memory and garbage collection

Not started

Objects are allocated on the heap and freed automatically once nothing can reach them from the roots (globals, the current stack, live closures). V8 splits the heap by age: short-lived objects are cleaned up cheaply and often, survivors are moved to an old generation that is collected less often, largely in the background.

Why it matters: A leak is just something still reachable: a forgotten event listener, a cache that only grows, or a closure holding a large object.

1

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 Map used as a cache with no limit or expiry;
  • a setInterval that 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.

⌘/Ctrl + Enter
OutputNot run yet

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.

2

Check yourself

2 questions. Get them all right to finish this topic.

  1. 1.When can an object be garbage collected?
  2. 2.Why can't you list the entries of a WeakMap?

0 of 2 right so far. Get all two to finish this topic.