JavaScript Interview Question #131

What are common causes of memory leaks in JavaScript?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

Common causes include long-lived global references, event listeners that are never removed, timers that continue running, unbounded caches, detached DOM nodes that remain referenced, and closures that retain large objects longer than required.

Detailed Explanation

Common causes include long-lived global references, event listeners that are never removed, timers that continue running, unbounded caches, detached DOM nodes that remain referenced, and closures that retain large objects longer than required.

Modern garbage collectors can handle cyclic references when they are unreachable. The key issue is reachability: if application code still has a live reference path to an object, the collector generally cannot reclaim it.

Code Example

const button = document.querySelector("#save");

function handleClick() {
    console.log("Saved");
}

button.addEventListener("click", handleClick);

// During component cleanup:
button.removeEventListener("click", handleClick);