An admin dashboard left open all day gets slower and slower. It was smooth in the morning, and by the afternoon the tab crashed (stopped suddenly). The code never changed. What kept changing is what sits in memory.
JavaScript cleans up memory by itself: the garbage collector (GC) throws away data your code can no longer reach. The trouble starts when the code still holds something it no longer uses. That data cannot be thrown away, and the memory keeps growing. This is called a memory leak. Picture a rented room that a cleaner tidies every week. The cleaner only throws away things nobody owns. If you stick a "mine" label on an old cardboard box and forget about it, the box is never thrown away, and the room gets more and more cramped. In JavaScript, the cleaner is the GC, and the labelled box is data that is not used but is still held by the code. The room getting cramped is the memory that keeps growing.
When memory is cleaned up
The GC starts checking from the roots, the things that are certainly still in use: global variables, window, the DOM shown on the page, and any listeners and timers still active. Everything reachable from those roots, through variables, properties or closures, counts as still in use. Whatever cannot be reached is thrown away. You do not need to (and cannot) call the GC yourself.
So a memory leak is memory that is no longer used but that the GC cannot free, because something still refers to it (some code still points to that data). The symptom: a page that is smooth at first gets slower the longer it is used, and the tab can crash. In DevTools, a healthy heap graph (the heap is the memory where JavaScript keeps its objects) goes up and down. A leaking one climbs like a staircase.
The four most common causes
This is the code of the modal in the Lab on this page. Each time it opens, it creates a modal element and a products array. In the Lab's model, the element is about 0.5 MB and the array about 2 MB. openModal opens the modal, then returns the function closeModal that closes it:
const infoModal = new WeakMap(); // a plain Map would keep the modal forever
function openModal() {
const modal = document.createElement("div");
const products = new Array(250000).fill("product"); // about 2 MB
const controller = new AbortController();
window.addEventListener("resize", () => positionModal(modal, products), {
signal: controller.signal,
});
const id = setInterval(() => refresh(modal, products), 1000);
infoModal.set(modal, { openedAt: Date.now() });
document.body.append(modal);
return function closeModal() {
modal.remove();
controller.abort(); // remove its listener
clearInterval(id); // stop its interval
};
}
The code above prevents the first three causes in this list with controller.abort(), clearInterval(id) and the WeakMap in the first line. The fourth cause explains why the leaks are big:
- A listener that is never removed.
windowlives as long as the page is open.windowholds the listener, and the listener is a closure holdingmodalandproducts. Withoutcontroller.abort(), those 2.5 MB stay in memory. - A timer that is never stopped.
setIntervalkeeps running every second untilclearInterval. Until then its callback and closure stay alive, along withmodalandproducts. - Detached DOM.
modal.remove()takes the element off the page. But if JavaScript still keeps a reference to it (for example, as a key in a plainMap), the element stays in memory. Such an element is called a detached DOM node (an element no longer attached to the page). - A closure holding big data. This cause is what makes the first two use so much memory. The closure in the interval only uses
productsto callrefresh, but as long as that closure lives, the 2 MB ofproductslive too.
One cause alone is enough to keep modal and products in memory. Say you remove the listener but forget clearInterval. The interval still holds the closure, so every open and close keeps 2.5 MB. Opening and closing five times makes 12.5 MB, and in the Lab the heap climbs from 8 MB to 20.5 MB.
Clean up on close
The rule: whatever you add when opening, remove when closing.
setIntervalreturns an id (the interval's number). Keep that id, then callclearInterval(id). Without the id, the interval cannot be stopped at all.- Remove a listener with
removeEventListener("resize", handler), using exactly the same function you added. - For many listeners at once, use an AbortController: pass
controller.signalto eachaddEventListener, and onecontroller.abort()removes them all. You don't need to keep a reference to every handler. The same signal can cancel afetchtoo.
WeakMap for data about elements
A plain Map holds its keys strongly. As long as an entry (a key and its value) exists, the element used as its key cannot be thrown away, even once it is off the page. A WeakMap holds its keys weakly. When nothing else refers to that element, its entry disappears when the GC runs. Use a WeakMap (or a WeakSet) to keep extra data about DOM elements, or about other objects that should be thrown away too. The cost: a WeakMap cannot be looped over and has no .size.
WeakRef is similar, but for one object: ref.deref() returns the object, or undefined once the GC has thrown that object away. Everyday code rarely needs WeakRef.
Finding a leak in DevTools
- Open DevTools, the Memory tab, choose Heap snapshot (a picture of what is in the heap at that moment), and click Take snapshot.
- Do the action you suspect, such as opening and closing the modal 5 times.
- Click the bin icon (Collect garbage) so all data that can be thrown away really is, then take a second snapshot.
- In the second snapshot, choose the Comparison view. Objects that grew in number but should be gone are the suspects. Type
Detachedin the filter box to find detached DOM nodes, then open the Retainers panel to see what still holds them.
Checking leak patterns in code text
In this lesson's exercise, code snippets are checked as text, with simple rules. The function findLeaks below does it:
function findLeaks(codeSnippets) {
const leaks = [];
codeSnippets.forEach((snippet, index) => {
if (snippet.includes("setInterval") && !snippet.includes("clearInterval")) {
leaks.push({ snippet: index, leak: "interval-not-cleared" });
}
if (snippet.includes("addEventListener") && !snippet.includes("removeEventListener")) {
leaks.push({ snippet: index, leak: "listener-not-removed" });
}
});
return leaks;
}
These are the results of findLeaks for three snippets:
| Call | Result |
|---|---|
findLeaks(["setInterval(() => update(), 1000)"]) |
[{ snippet: 0, leak: "interval-not-cleared" }] |
findLeaks(["const t = setInterval(() => {}, 1000); clearInterval(t)"]) |
[] |
findLeaks(['document.addEventListener("click", fn)']) |
[{ snippet: 0, leak: "listener-not-removed" }] |
forEach((snippet, index) => ...)gives each snippet's text and its position, starting at 0.includeschecks whether a word appears in that text.- Each finding has the shape
{ snippet, leak }. In the exercise,snippetmust be written first, thenleak.
⚠️ Why does memory keep climbing?
setIntervalwithout keeping its id.setInterval(() => checkStatus(), 1000)can never be stopped, so its callback and closure live forever.removeEventListenerwith a new function.removeEventListener("click", () => openModal())removes nothing, because that arrow function is not the one you added. Keep the handler in a variable, or use an AbortController.- Keeping elements in a
Mapor a global array. The element becomes a detached DOM node afterremove(). Use aWeakMap, or delete the entry when closing. - Treating
findLeaksas a real checker.findLeaksonly reads text. A listener removed throughcontroller.abort()still counts as a leak, because the wordremoveEventListeneris not there.
TL;DR: JavaScript cleans up memory by itself with the GC (garbage collector). A memory leak is memory that is no longer used but that the GC cannot free, because something still refers to it (some code still points to that data). The most common causes: listeners never removed, setInterval without clearInterval, detached DOM nodes (elements taken off the page but still kept in JavaScript), and closures holding big data. One cause is enough to keep memory growing. In the Lab, a 2.5 MB modal has an interval nobody stopped. After that modal is opened and closed 5 times, the heap (the memory where objects are kept) has grown from 8 MB to 20.5 MB. Remove everything on close: clearInterval(id), removeEventListener with the same function, or one controller.abort() for many listeners. Keep data about elements in a WeakMap (a Map that doesn't keep its keys alive). Find leaks with two heap snapshots (pictures of what is in memory) in the Memory tab and the Comparison view.
⚡ Memory that can't be thrown away
Guess first: JavaScript cleans up memory by itself with a garbage collector. So what is a memory leak?
Memory that is no longer used but that the garbage collector cannot free, because some code still points to that data.
Meaning: The garbage collector only throws away data that can no longer be reached from the roots: global variables, window, the DOM on the page, and listeners and timers still active. The symptom of a memory leak: the page gets slower, and the heap graph in DevTools (the heap is the memory where JavaScript keeps its objects) climbs like a staircase.
⚡ Clean up on close
Write:
return function closeModal() {
modal.remove();
controller.abort();
clearInterval(id);
};
Meaning: This is the function that closes the modal. When it opened, the modal added a listener that uses the signal of controller (an AbortController), and an interval whose number is kept in id. Whatever you add when opening, remove when closing. modal.remove() takes the modal off the page. One controller.abort() removes every listener that uses its signal, and clearInterval(id) stops the interval. Forgetting one of them is enough to keep memory growing: in the Lab, with a forgotten interval, a modal opened and closed 5 times takes the heap from 8 MB to 20.5 MB.
⚡ WeakMap and heap snapshots
Meaning: Keep data about elements in a WeakMap (a Map that doesn't keep its keys alive), so the data is thrown away with the element. To find a leak, take two heap snapshots (pictures of what is in memory) in the DevTools Memory tab, before and after the action you suspect. Then compare them in the Comparison view.