logo

Heap & Garbage Collection

Overview of memory allocation in JavaScript, heap vs stack, and how garbage collection works at a high level.

Short explanation

JavaScript uses a heap for dynamic memory and a stack for execution contexts. The garbage collector reclaims memory that is no longer reachable by the program, using strategies like mark-and-sweep.

Small snippet

let bigArray = new Array(1000000).fill(0);
// When bigArray is set to null, memory becomes eligible for GC
bigArray = null;

How JS handles it internally

Objects and closures that are still referenced from reachable roots (like global objects or active stack frames) cannot be collected. Engines periodically pause execution to run GC phases; modern GCs are incremental and generational to reduce pause times.

Diagram

diagram-placeholder

FAQ

Q: Will GC always free memory immediately when I set a variable to null?

A: No. GC runs on the engine's schedule; setting to null only makes the memory eligible for collection.