HeadlinesBriefing favicon HeadlinesBriefing.com

JavaScript Garbage Collector Explained

DEV Community •
×

A slow dashboard reveals a core JavaScript concept: the Heap. When browser performance lags, developers often blame heavy calculations. The culprit is usually unmanaged memory. JavaScript automatically handles memory allocation, but its Garbage Collector (GC) follows strict reachability rules to reclaim unused space. Understanding this process is key to diagnosing and fixing performance issues.

The GC uses a Mark-and-Sweep algorithm. It starts at Roots like the global `window` object and traces all References. Objects connected to a root are marked safe. Any object unreachable from a root is considered garbage and swept away. This automated process prevents manual memory management but requires developers to understand how references are created and broken.

A common memory leak occurs with event listeners. Attaching a listener to the window creates a persistent reference chain. Even after a function completes, the listener's closure can hold onto large datasets, preventing garbage collection. The solution is to explicitly removeEventListener, breaking the reference chain and allowing the GC to reclaim the memory.