🟡 MediumCore JS📖 Theory Question

How does garbage collection work in JavaScript?

💡

Hint

Mark-and-sweep — unreachable objects are collected; common leak sources

Full Answer

JavaScript uses automatic garbage collection — memory is freed when objects become unreachable from the "roots" (globals + active call stack).

Mark-and-Sweep algorithm:

  1. Start from roots (global scope + call stack)
  2. Mark every reachable object
  3. Sweep — free everything NOT marked
let user = { name: 'Alice' }; // reachable via 'user'
user = null;                  // reference dropped → unreachable → GC'd

// Circular reference — NOT a problem for modern mark-and-sweep
let a = {}; let b = {};
a.ref = b; b.ref = a; // circular — but if a and b lose all external refs, both are GC'd

Common memory leak sources:

  • Forgotten setInterval holding references to DOM elements
  • Detached DOM nodes still referenced in JS variables
  • Event listeners never removed (removeEventListener)
  • Closures unintentionally capturing large objects
  • Unbounded caches / global arrays that grow forever
💡 Use WeakMap/WeakRef to associate data with objects without preventing GC. DevTools Memory tab → Heap Snapshot to hunt leaks.

More Core JS Questions

🟢 EasyWhat is the difference between var, let, and const?→🟢 EasyExplain closures with a practical example.→🟢 EasyWhat is hoisting in JavaScript?→🟢 EasyExplain the event loop, call stack, and microtask queue.→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint