How does JavaScript garbage collection work?
By FrontendPro Editorial Team Updated 8/8/2026
Answer
Garbage collection in JavaScript is an automatic memory management mechanism that reclaims memory occupied by objects and variables that are no longer in use by the program. The two most common algorithms are mark-and-sweep and generational garbage collection.
Mark-and-sweep
The most common garbage collection algorithm used in JavaScript is the Mark-and-sweep algorithm. It operates in two phases:
- Marking phase: The garbage collector traverses the object graph, starting from the root objects (global variables, currently executing functions, etc.), and marks all reachable objects as "in-use".
- Sweeping phase: The garbage collector sweeps through memory, removing all unmarked objects, as they are considered unreachable and no longer needed.
This algorithm effectively identifies and removes objects that have become unreachable, freeing up memory for new allocations.
Generational garbage collection
Leveraged by modern JavaScript engines, objects are divided into different generations based on their age and usage patterns. Frequently accessed objects are moved to younger generations, while less frequently used objects are promoted to older generations. This optimization reduces the overhead of garbage collection by focusing on the younger generations, where most objects are short-lived.
Different JavaScript engines (which differ across browsers) implement different garbage collection algorithms and there's no standard way of doing garbage collection.
<br><br> <!-- QUESTIONS:TOP:END -->Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
