JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

Memory Management & Garbage Collection

javascript
senior
memory

How does JavaScript garbage collection work and how can you prevent memory leaks?

memory
garbage-collection
memory-leaks
performance
weakmap
Quick Answer

JavaScript uses automatic garbage collection with a mark-and-sweep algorithm. Objects are collected when unreachable from roots (global, stack). Memory leaks occur from uncleared references like closures, event listeners, intervals, and DOM references.

Detailed Explanation

Garbage Collection Basics:

  • JavaScript automatically manages memory
  • Modern engines (V8) use generational GC: young generation objects are collected via a fast scavenger, long-lived old generation objects use mark-sweep-compact
  • Both phases use concurrent and parallel techniques to minimize pauses
  • Objects are collected when unreachable from 'roots'

Root References:

  • Global variables
  • Current call stack
  • Closures referencing variables

Common Memory Leaks:

  1. Forgotten timers/intervals: setInterval without clearInterval
  2. Detached DOM elements: JS references to removed DOM nodes
  3. Closures: Unintentionally capturing large scopes
  4. Event listeners: Not removed when elements are destroyed
  5. Global variables: Accidental globals via missing 'let/const'
  6. Circular references: (mostly handled by modern GC)

Prevention Strategies:

  • Use WeakMap/WeakSet for caches
  • Remove event listeners on cleanup
  • Clear intervals and timeouts
  • Nullify references when done
  • Use browser DevTools Memory profiler
  • Consider WeakRef for caches where GC should reclaim values (ES2021)
  • Use FinalizationRegistry for cleanup callbacks when objects are collected (ES2021, non-deterministic)

Code Examples

Common memory leak patternsJavaScript
// LEAK 1: Forgotten interval
function startPolling() {
  setInterval(() => {
    fetch('/api/data').then(updateUI);
  }, 1000);
  // Never cleared! Runs forever.
}

// FIX: Store and clear
let pollInterval;
function startPolling() {
  pollInterval = setInterval(/* ... */);
}
function stopPolling() {
  clearInterval(pollInterval);
}

// LEAK 2: Event listeners not cleaned up
class ComponentBad {
  constructor() {
    window.addEventListener('resize', this.handleResize);
  }
  // Missing cleanup! Listener persists after component destroyed.
}

// FIX: Add destroy method
class ComponentFixed {
  constructor() {
    this.handleResize = this.handleResize.bind(this);
    window.addEventListener('resize', this.handleResize);
  }
  destroy() {
    window.removeEventListener('resize', this.handleResize);
  }
}

Real-World Applications

Use Cases

SPA Route Transition Cleanup

Ensuring event listeners, WebSocket connections, intervals, and detached DOM nodes are properly cleaned up when navigating between routes

Real-Time Dashboard Memory Management

Managing memory in dashboards receiving continuous WebSocket data using ring buffers and WeakRef-based caches to prevent unbounded growth

Image Gallery Lazy Loading

Releasing decoded image data for off-screen images using IntersectionObserver cleanup and WeakRef caching for re-display

Mini Projects

Memory Leak Detector

intermediate

Build a utility wrapping addEventListener, setInterval, and setTimeout to track active listeners and timers, reporting potential leaks

WeakRef Cache with FinalizationRegistry

advanced

Implement a cache using WeakRef for values and FinalizationRegistry for cleanup logging, with hit/miss statistics

Industry Examples

Meta

Built and open-sourced MemLab, a memory testing framework that automates leak detection in single-page applications

Google Chrome DevTools

Provides heap snapshot comparison, allocation timeline, and sampling tools for JavaScript memory leak detection

Resources

MDN - Memory Management

docs

Chrome DevTools - Fix memory problems

article

Related Questions

What are WeakMap and WeakSet, and how do they differ from Map and Set?

mid
weakrefs
Previous
What are Proxies in JavaScript and how can they be used?
Next
Explain the Module pattern and how ES6 modules differ from CommonJS.
PrevNext