Learn JavaScript
❯ variables.memory_gc

Memory & Garbage Collection in JavaScript

$concept

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.

$how it works
1

Allocate implicitly

Every object literal, array, closure, and string allocates — no keywords, no sizes, no manual steps.

2

Collect the unreachable

The GC traces from roots and frees the rest — dropping the last reference is the entire deallocation protocol.

3

Leaks are retention

Timers, listeners, caches, and closures holding big scopes keep objects reachable — and therefore alive — forever.

4

Release deliberately

clearInterval, removeEventListener, null out caches, scope closures tightly — hygiene replaces free().

$example
let cache = { a: 1 };
cache = null;
console.log("released:", cache === null);
Output
released: true
1The object starts reachable through cache — alive and collectible-proof.
2Reassigning null drops the last reference, making the object unreachable and eligible for collection.
3released: true prints — collection itself happens on the engine's schedule, eligibility is immediate.
$use cases
Clearing timers and listeners when components unmount
Bounding caches (LRU, size caps, WeakMap) instead of growing forever
Diagnosing growth with heap snapshots in DevTools Memory tab
Scoping closures narrowly so they don't retain whole outer worlds

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.