🟢 EasyPerformance📖 Theory Question

What causes memory leaks in JavaScript and how do you detect them?

💡

Hint

Unintentional references prevent GC: forgotten timers, closures, detached DOM nodes

Full Answer

Memory leaks occur when objects are no longer needed but are still referenced, preventing garbage collection.

Common causes:

// 1. Forgotten intervals
const el = document.getElementById('status');
const id = setInterval(() => { el.innerHTML = Date.now(); }, 1000);
// If el is removed from DOM but interval isn't cleared → leak
// Fix: clearInterval(id) when done

// 2. Detached DOM nodes
let detached;
function create() {
  detached = document.createElement('div'); // global reference
  document.body.appendChild(detached);
  document.body.removeChild(detached); // removed from DOM...
  // but 'detached' variable still holds it → leak
}

// 3. Closures capturing large objects
function leaky() {
  const bigData = new Array(1_000_000).fill('*');
  return () => bigData[0]; // ALL of bigData kept alive!
}

// 4. Event listeners not removed
window.addEventListener('resize', heavyHandler);
// Fix: window.removeEventListener('resize', heavyHandler) on cleanup

// 5. Growing caches without eviction
const cache = {};
function store(key, val) { cache[key] = val; } // never cleared!

Detection: Chrome DevTools → Memory → Heap Snapshot → look for "Detached" DOM nodes, or compare snapshots over time for growing retained size.

💡 Use WeakMap for object-keyed caches — entries are automatically released when the key object is GC'd. Perfect for per-element data storage.

More Performance Questions

🟢 EasyWhat are debounce and throttle? When do you use each?→🟢 EasyWhat is the difference between reflow and repaint, and how do you avoid layout thrashing?→🟡 MediumWhat is lazy loading and code splitting?→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint