Home
← All questions

How does memory allocation work in JavaScript?

MediumPremiumJavaScript

JavaScript interview practice: Explain the stack vs heap, garbage collection, and common memory leaks.

Answer

JavaScript manages memory automatically in two regions:

  • Stack — stores primitives (number, string, boolean, null, undefined, symbol, bigint) and references. Fixed size, fast, LIFO.
  • Heap — stores objects, arrays, and functions. Variables hold a reference (pointer) into the heap.

Lifecycle: allocate → use → release. Release is handled by the garbage collector using the mark-and-sweep algorithm: starting from roots (global, call stack), it marks all reachable objects; anything unreachable is swept (freed).

Common memory leaks:

  • Forgotten timers/intervals and event listeners.
  • Closures holding large objects longer than needed.
  • Detached DOM nodes still referenced in JS.
  • Growing global caches/maps (use WeakMap/WeakRef for cache keyed by objects).
let a = 10;             // primitive -> stack
let obj = { x: 1 };     // object -> heap, 'obj' holds a reference on the stack
let ref = obj;          // copies the reference, same heap object
ref.x = 99;
console.log(obj.x);     // 99 (same object)
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium