Breaking Reference Cycles
What you'll learn: How mark-and-sweep garbage collection handles circular references that would break simpler reference counting systems.
The Problem with Reference Counting
Imagine a simple garbage collection approach that just counts how many references point to each object. When the count hits zero, the object is freed. Sounds logical, right?
But consider two objects that reference each other:
let objA = {};
let objB = {};
objA.friend = objB;
objB.friend = objA;
// Now remove our references
objA = null;
objB = null;
With reference counting, both objects still have a count of 1 (they reference each other), even though they're completely unreachable from your program. They'd never be collected—a memory leak!
Why Mark-and-Sweep Wins
Mark-and-sweep doesn't care about reference counts. It only cares about reachability from roots.
When the garbage collector runs:
- Mark phase: Start from roots (global scope, call stack), follow every reference chain, mark everything reachable
- Sweep phase: Delete everything not marked
In the example above, when objA and objB are set to null, there's no path from any root to either object. Even though they reference each other, the mark phase never reaches them. Result? Both get swept away.
Think of it like a lighthouse: mark-and-sweep only illuminates what it can reach from shore (roots). Two boats tied together in the middle of the ocean (circular reference) won't be illuminated just because they're connected to each other—they're still unreachable from land.
Key Takeaway: Mark-and-sweep correctly collects circular references because it traces reachability from roots rather than counting references, making JavaScript's automatic memory management robust against common reference cycle patterns.