JavaScript Runtime6h estimated

Garbage Collection

Difficulty
Importance

The problem

Every object created during a program's run consumes memory, and if nothing ever freed it, a long-running program would eventually exhaust all available memory — garbage collection automatically reclaims memory for objects that can no longer be reached, without the programmer manually tracking every allocation.

Why now

Memory, the stack & the heap already established that heap-allocated objects have unpredictable lifetimes and don't disappear automatically like stack frames do; garbage collection is JavaScript's specific answer to reclaiming that heap memory once it's no longer needed, using reachability through the reference chains mutability-and-references already described.

Mental model

An object is garbage exactly when nothing reachable from a program's roots (global variables, the current call stack) still references it, directly or through a chain of other objects — the collector periodically walks those chains and frees anything it can't reach. A memory leak in a garbage-collected language isn't forgetting to free something; it's accidentally keeping a reference alive to something you meant to be unreachable.

Requires

Unlocks

Used in

Projects

  • Deliberately create a memory leak by accumulating references in a growing array that's never cleared, and observe memory growth in a profiler
  • Explain, for a small object graph diagram, exactly which objects are reachable from the roots and which would be collected

Examples

  • A global array that keeps growing with event listener references, never removed, is a classic memory leak — the objects stay reachable forever
  • A closure that captures a large unused object keeps that object alive in memory for as long as the closure itself is reachable

Resources

Mastery checklist