The Sweep Phase
What you'll learn: How the garbage collector reclaims memory from objects that weren't marked as reachable during the mark phase.
How Sweeping Works
After the mark phase completes, the garbage collector enters the sweep phase. Think of this like a cleanup crew going through a building after an inspection: any room (object) without a "keep this" sticker (mark) gets cleared out.
During the sweep phase, the garbage collector:
- Scans through all allocated memory in the heap
- Identifies unmarked objects — these are no longer reachable from any root
- Frees their memory, making it available for future allocations
- Clears marks from surviving objects, preparing for the next garbage collection cycle
The Cleanup Process
Imagine a parking lot after an event. The mark phase identified which cars have valid tickets. Now, the sweep phase goes space by space:
- Marked space? Leave it alone, just remove the ticket for next time
- Unmarked space? This car was abandoned — tow it away and mark the space as available
The memory previously occupied by unreachable objects is added back to the free memory pool. The JavaScript engine can now use this reclaimed space for new objects you create.
The Complete Mark-and-Sweep Cycle
The mark and sweep phases work together as the fundamental garbage collection algorithm. Mark identifies what's alive; sweep removes what's dead. This cycle repeats automatically whenever the engine determines memory needs to be reclaimed — you never trigger it manually.
Key Takeaway: The sweep phase completes garbage collection by scanning memory, identifying all unmarked (unreachable) objects, freeing their memory, and resetting marks on surviving objects for the next cycle.