Memory Management and Garbage Collection

Advanced · 27 min

How a JS engine decides what memory to reclaim and when, mark-and-sweep, and the everyday leaks — forgotten timers, listeners, closures.

Before thisPrototypal Inheritance and Object.createClosures

JSHeroes · 27 min

Memory Management and Garbage Collection

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by JSHeroesReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • JavaScript never makes you allocate or free memory by hand — the engine allocates space for every value you create and, separately, decides later when that space can be reclaimed. Garbage collection is the automation of that second step, not the first.
  • Reachability, not age, is what decides whether something gets collected: a value is kept alive as long as something still leads back to it from a root (the global object, or anything on the current call stack) — through a variable, a closure, or a property chain — and reclaimed the moment nothing does anymore.
  • Mark-and-sweep is the core algorithm: starting from the roots, the collector marks every value it can still reach, then sweeps through memory and frees everything that didn't get marked. Most engines also split memory into generations — a small, frequently-collected area for new objects and a larger one for long-lived survivors — because most objects turn out to be short-lived, so collecting that area often is cheap and pays off.
  • A "memory leak" in JavaScript doesn't mean memory got corrupted — it means something is still reachable that the program will never actually use again, usually because a `setInterval`/`setTimeout` was never cleared, an event listener was never removed, or a closure is holding onto a variable it doesn't need anymore just because it's defined in the same scope as one it does.
  • Detached DOM nodes — keeping a JavaScript reference to an element after removing it from the page — are one of the most common real-world leaks, but they're specific to the browser's DOM and belong to `frontend`'s territory; this lesson stays at the engine-level mechanics that apply everywhere JavaScript runs.

The problem automatic memory management is solving

In a language like C, memory is your problem. You ask for a block with malloc, and it’s yours until you explicitly hand it back with free. Get that wrong in either direction — free something too early and a later read touches memory that’s since been reused for something else, or forget to free it at all — and you’ve introduced a bug that can take hours to trace back to its actual cause, because the crash happens somewhere completely unrelated to the mistake.

JavaScript sidesteps the first half of that problem entirely. You never call anything like malloc or free. Every time you create a value — an object literal, an array, a function — the engine allocates space for it without you asking. The part that still matters to understand is the other half: how does the engine ever decide it’s safe to take that memory back?

Reachability is the entire question

The engine doesn’t track how long a value has existed, or how many times it’s been used, or anything like that. It tracks one thing: can you still get to this value by following references, starting from a fixed set of roots — the global object, plus everything currently on the call stack, including local variables and the variables a closure has captured?

function makeCounter() {
  let count = 0; // not a root itself, but reachable through the closure
  return () => ++count;
}

let counter = makeCounter();
counter(); // 1
counter = null; // the returned function is now unreachable...
               // ...and so, transitively, is `count`

While counter holds the returned function, that function is reachable from a root (the counter variable), which keeps the closed-over count reachable too — closures are exactly the mechanism that keeps a variable alive past the point its own function call ended. The moment you reassign counter, nothing leads back to that function anymore, and count goes down with it. Nothing about using count less, or using it a long time ago, matters — only whether something still points to it, right now.

Mark-and-sweep, and why engines split the heap

The actual algorithm most engines use to answer “what’s reachable?” is called mark-and-sweep, and it’s genuinely simple once you see it in two steps. Mark: starting from the roots, follow every reference outward and flag everything you reach as still live. Sweep: walk through memory, and reclaim everything that never got flagged — by definition, nothing in the program could have reached it, so nothing can possibly use it going forward.

Engines like V8 add one more idea on top: most objects die almost immediately after they’re created — a temporary variable inside a function, an intermediate array in a map chain — while a smaller set survive for a long time. Knowing that, V8 splits its heap into a young generation, scanned often and cheaply because it’s small and most of what’s in it is already garbage, and an old generation for objects that survive long enough to prove they’re not temporary, which gets the full, more expensive mark-and-sweep pass much less frequently. This is generational garbage collection, conceptually: collect the part that’s usually garbage often, and the part that usually isn’t garbage rarely.

Leaks in a language with garbage collection

It sounds like a contradiction — if the collector reclaims anything unreachable, how do JavaScript programs leak memory at all? The answer: by accidentally keeping things reachable on purpose. Three patterns cause most real leaks in plain JavaScript:

Forgotten timers. A setInterval or setTimeout that’s never cleared keeps its callback reachable indefinitely — and since that callback is usually a closure, everything it references stays reachable with it, for as long as the timer keeps running. clearInterval/clearTimeout isn’t just cleanup etiquette; it’s removing a root.

Forgotten listeners. element.addEventListener('click', handler) keeps handler reachable from the element for as long as the listener is attached, which keeps anything handler closes over reachable too. Never calling removeEventListener means that chain of references just accumulates for the lifetime of the page.

Over-eager closures. A closure captures variables, not just the ones it uses — if a function closes over a large object but only ever reads one small field off it, the entire object stays reachable for as long as the closure does, not just the field that’s actually needed.

Detached DOM nodes — holding onto a reference to an element after removing it from the document — are the leak pattern you’ll hear about most in practice, but that one’s specific to the browser’s DOM tree and belongs to frontend’s coverage of the subject; it isn’t gone into further here on purpose.

How the embedded video fits in

The embedded talk visualizes the generational mark-and-sweep process step by step inside a real engine, which lines up directly with the reachability and generational-heap sections above. The two “go deeper” links take this further in different directions: the Web Dev Simplified video spends real time on debugging and fixing the common memory-related problems from the previous section, and the Computerphile video strips mark-and-sweep down to the general computer-science algorithm, independent of any one language, if you want to see the idea in its most basic form.

Where this fits in the path

This closes out the roadmap’s advanced group by leaning on two things you’ve already built up: prototypal inheritance (so you understand that a prototype chain is itself just another set of references the collector has to follow when deciding reachability) and closures (which, as the counter example above shows, are one of the most common — and most commonly misunderstood — reasons something stays reachable longer than you expect). Understanding this is what separates reading JavaScript from understanding what it’s actually doing underneath you while your program runs.

Check yourself

  1. 01In C, you call `malloc` and `free` yourself. What does JavaScript do instead, and what's the actual tradeoff?

    JavaScript allocates memory for you automatically when you create a value, and a garbage collector automatically reclaims it later once nothing can reach it anymore — you never call anything like `free`. The tradeoff is that you give up precise control over exactly when memory is reclaimed, in exchange for eliminating an entire category of manual-memory bugs (use-after-free, double-free, forgetting to free at all).

  2. 02What determines whether the garbage collector can reclaim a given object — how long it's existed, or something else?

    Reachability, not age or lifetime. An object is kept alive as long as there's a path to it from a root — a global variable, something on the current call stack, a closure variable — through references. The instant nothing leads back to it anymore, it becomes eligible for collection, regardless of how old or new it is.

  3. 03Describe mark-and-sweep in your own words: what are the two phases, and what does each one do?

    The mark phase starts at the roots and follows every reference outward, marking every object it reaches as still in use. The sweep phase then goes through memory and reclaims every object that didn't get marked in the first phase — those are the ones nothing could reach, so nothing in the program can possibly use them anymore.

  4. 04Why do many engines split the heap into a "young generation" and an "old generation" instead of just running one mark-and-sweep pass over everything?

    Because most objects turn out to be very short-lived — created, used briefly, and discarded. Running a full collection over the entire heap every time is wasteful when most of what you'd scan just gets reclaimed anyway. Collecting the young generation frequently (where short-lived objects live and die) is cheap, and only running the more expensive full collection over the old generation occasionally keeps the common case fast.

  5. 05You set up a `setInterval` inside a component or module and never call `clearInterval` on it. Why does this leak memory even if the interval's callback does nothing harmful?

    The running interval itself is a root that keeps its callback function reachable indefinitely, and that callback — being a closure — keeps everything it references reachable too, including the entire scope it was defined in. Nothing about what the callback *does* has to be harmful; the leak is simply that the collector can never reclaim any of that scope, because the uncancelled timer never stops counting as a reason something is still "in use".

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark