When GC Runs
What you'll learn: You'll understand that JavaScript's garbage collector runs automatically and unpredictably, not under your direct control.
You Don't Control the Schedule
Unlike some languages where you can explicitly trigger garbage collection, JavaScript's GC is non-deterministic. This means you cannot predict exactly when it will run. The engine decides based on internal heuristics and memory pressure.
Memory Pressure Triggers GC
The garbage collector typically runs when:
- Memory usage increases significantly
- The heap (memory allocated for objects) reaches certain thresholds
- The engine detects it's a good time (low CPU activity)
- Long periods have passed since the last collection
Think of it like a smart janitor in an office building. They don't clean on a fixed schedule you control. Instead, they monitor how messy things are getting and clean when needed, preferably when fewer people are working.
Why This Matters
Because GC timing is unpredictable:
- You cannot force cleanup of unreachable objects immediately
- Setting references to
nulldoesn't instantly free memory - Performance impacts from GC pauses happen at engine-determined moments
- Your code should never rely on GC running at specific times
The engine is optimized to run GC efficiently, often during idle moments to minimize disruption to your application's performance.
Implications for Your Code
Since you can't control when GC runs, focus on what you can control: breaking references when you're done with objects (as you learned in the previous lesson). The engine will handle the actual cleanup on its own schedule.
Key Takeaway: JavaScript's garbage collector runs automatically when the engine detects memory pressure or optimal conditions—you cannot predict or force when it executes, so write code that helps GC by breaking unnecessary references rather than trying to control the cleanup timing.