Memory & Garbage Collection in JavaScript
JavaScript manages memory automatically: allocation happens on use (objects, closures, strings), and the garbage collector reclaims whatever becomes unreachable — typically via mark-and-sweep from roots (globals, stack, closures). You never free, and must rarely think about it — except for the leaks that automatic management can't prevent.
Real-world leaks are retention bugs, not missing frees: forgotten timers/intervals, unremoved event listeners, ever-growing caches and arrays, and detached DOM trees kept alive by stray references. WeakMap/WeakSet (covered in Collections) let caches hold without preventing collection.
Allocate implicitly
Every object literal, array, closure, and string allocates — no keywords, no sizes, no manual steps.
Collect the unreachable
The GC traces from roots and frees the rest — dropping the last reference is the entire deallocation protocol.
Leaks are retention
Timers, listeners, caches, and closures holding big scopes keep objects reachable — and therefore alive — forever.
Release deliberately
clearInterval, removeEventListener, null out caches, scope closures tightly — hygiene replaces free().
let cache = { a: 1 };cache = null;console.log("released:", cache === null);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.