Learn the concept
Memory Management & Garbage Collection
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.
Garbage Collection Basics:
Root References:
Common Memory Leaks:
Prevention Strategies:
// 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);
}
}Ensuring event listeners, WebSocket connections, intervals, and detached DOM nodes are properly cleaned up when navigating between routes
Managing memory in dashboards receiving continuous WebSocket data using ring buffers and WeakRef-based caches to prevent unbounded growth
Releasing decoded image data for off-screen images using IntersectionObserver cleanup and WeakRef caching for re-display
Build a utility wrapping addEventListener, setInterval, and setTimeout to track active listeners and timers, reporting potential leaks
Implement a cache using WeakRef for values and FinalizationRegistry for cleanup logging, with hit/miss statistics