Event Listeners That Never Get Removed
You'll learn why event listeners can cause memory leaks and how to properly clean them up.
Why Event Listeners Hold References
When you attach an event listener to a DOM element, JavaScript creates a reference from that element to your callback function. But here's the catch: the callback also captures references to anything in its scope (through closure). This means the element, the callback, and everything the callback references all stay in memory—even if you think you're done with them.
The Problem
Imagine you create a temporary UI component, attach event listeners to it, then remove it from the DOM. You'd expect garbage collection to clean it up, right? Not if the listeners are still registered. The detached element remains in memory, kept alive by the listener reference. Multiply this by dozens of components being created and destroyed, and you have a memory leak.
function showModal() {
const modal = document.createElement('div');
const closeBtn = document.createElement('button');
// This listener keeps modal alive even after removal
closeBtn.addEventListener('click', () => {
modal.remove();
// Oops! Listener still attached to closeBtn
});
document.body.appendChild(modal);
}
The Solution
Always use removeEventListener when you're done, or use patterns that auto-cleanup:
function showModal() {
const modal = document.createElement('div');
const closeBtn = document.createElement('button');
const handleClose = () => {
modal.remove();
closeBtn.removeEventListener('click', handleClose); // Cleanup!
};
closeBtn.addEventListener('click', handleClose);
document.body.appendChild(modal);
}
Key Takeaway: Event listeners create strong references that prevent garbage collection. Always clean up listeners with removeEventListener or use the { once: true } option when appropriate to avoid memory leaks.