JavaScript › Memory Management & Garbage Collection
How does mark-and-sweep garbage collection actually determine which objects are reachable?
AdvancedAnswer
The collector starts from a set of 'roots' (global objects, currently executing call stack, active closures) and traverses every reference reachable from them, marking each visited object as live; anything left unmarked after this traversal is unreachable garbage and gets swept (freed).
// Roots -> traversal example (conceptual)
// window -> app -> currentUser -> profile (all marked reachable)
// an object with zero incoming references from any root is sweptReal-world example Explaining why two objects that only reference EACH OTHER, but nothing else references them, are still correctly collected (unlike naive reference counting).