Garbage Collection
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
- Memory, the Stack & the HeapComputer Science Fundamentals
Garbage collection specifically manages heap memory, as distinct from the stack; you need that distinction already in place to know which memory region garbage collection is even responsible for.
- Mutability & ReferencesProgramming Fundamentals
Reachability — the criterion garbage collection uses to decide what to free — is defined entirely in terms of reference chains between objects, exactly the aliasing/reference model already covered.
Unlocks
Used in
- Every JavaScript runtime's automatic memory management, requiring no manual free() calls
- Memory leak debugging in long-running Node.js servers and single-page applications
- Closures accidentally retaining large objects in memory longer than intended
- Browser DevTools' memory profiler, built around visualizing the reachability graph
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
- MDN — Memory managementarticle
Mastery checklist
- I can explain reachability as the criterion garbage collection uses to reclaim memory
- I can explain what a memory leak means in a garbage-collected language
- I can identify a closure or global reference that's unintentionally keeping an object alive
- I can use browser DevTools to inspect memory usage and find a leak