QA
Senior LevelJavaScript & TypeScript

What are common JavaScript memory leaks and how do you detect them?

❓ Interview Prompt: Explain common memory leak patterns, detached DOM nodes, closures, and Chrome DevTools memory profiling.

Common Memory Leak Patterns:

1
Forgotten timers/intervals: setInterval without clearInterval keeps the callback and its closure alive.
2
Detached DOM nodes: Removing a DOM element but keeping a JavaScript reference prevents garbage collection.
3
Closure-captured variables: A closure accidentally retains a large object that's no longer needed.
4
Event listeners not removed: Listeners on removed DOM elements prevent GC.
5
Growing Map/Set caches: Unbounded caches that never evict entries.

Detection (Chrome DevTools):

1
Memory tab → Heap Snapshot: Compare snapshots to find objects that should have been collected.
2
Allocation timeline: Shows objects allocated over time.
3
Performance Monitor: Watch JS Heap Size for continuous growth.

Code Implementation Example

javascript
// ❌ Memory leak: forgotten interval
function startPolling() {
  setInterval(() => {
    const data = fetchLargeData();
    updateUI(data);
  }, 1000);
  // No cleanup! Runs forever.
}

// ✅ Fix: store and clear interval
class Poller {
  #intervalId = null;
  start() {
    this.#intervalId = setInterval(() => this.poll(), 1000);
  }
  stop() {
    clearInterval(this.#intervalId);
    this.#intervalId = null;
  }
}
💡Memory leak patterns and fixes for timers and detached DOM nodes.
🎯 Interview Key Takeaway

Always clear timers, remove event listeners, and nullify DOM references when elements are removed.

#Memory Leaks#Garbage Collection#DevTools#Senior
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?