Accidental Memory Leaks with Event Listeners
You'll learn: How event listeners that capture large objects in closures can prevent garbage collection and cause memory leaks.
The Problem with Long-Lived Listeners
When you add an event listener that closes over variables, those variables remain in memory as long as the listener exists. This is normally fine, but becomes a memory leak when:
- The listener captures a large object or data structure
- The listener stays attached longer than needed
- You forget to remove the listener when done
Think of it like keeping a key to a storage unit you no longer use—the storage company can't rent it to anyone else because technically you still have access.
How It Happens
function attachHandler() {
const largeData = new Array(1000000).fill('data');
document.getElementById('btn').addEventListener('click', function() {
console.log(largeData[0]); // Closure captures entire array
});
// largeData can't be garbage collected while listener exists
}
attachHandler();
// Even after function returns, largeData stays in memory!
The event listener creates a closure over largeData. Since the listener remains attached to the DOM, JavaScript keeps the entire array alive indefinitely.
The Solution
Always remove event listeners when you're done:
function attachHandler() {
const largeData = new Array(1000000).fill('data');
function handler() {
console.log(largeData[0]);
}
const btn = document.getElementById('btn');
btn.addEventListener('click', handler);
// Later, when no longer needed:
btn.removeEventListener('click', handler);
// Now largeData can be garbage collected
}
Key Takeaway: Event listeners that close over large objects keep those objects in memory until removed—always clean up listeners to prevent memory leaks.