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 Component {
constructor() {
window.addEventListener('resize', this.handleResize);
}
// Missing cleanup! Listener persists after component destroyed.
}
// FIX: Add destroy method
class Component {
constructor() {
this.handleResize = this.handleResize.bind(this);
window.addEventListener('resize', this.handleResize);
}
destroy() {
window.removeEventListener('resize', this.handleResize);
}
}