The admin dashboard has been open since morning. By one o'clock it gets slow, and by late afternoon the tab crashes (it stops and shows an error page). Refresh it, and everything runs smoothly again, until the next afternoon. That's the classic sign of a memory leak: memory a program has allocated (taken to store data) but never frees (gives back). The reason: some reference still holds that data. A reference here is a variable, array or object that still keeps the data.
The causes of a leak (listeners, timers, closures) are covered in the Memory Management lesson of the Performance track. This lesson is about finding one: proving that memory keeps rising, then finding which part of the code still holds data that should have been thrown away. It works like looking for a leaking pipe at home. You turn off every tap, note the number on the water meter, wait, and note it again. If the number keeps rising while nobody uses water, something leaks. Only then do you check the pipes one by one. In this lesson, the water meter is the memory number, and the pipes you check are the chain of references that holds the data.
The symptom: it keeps rising, not rising once
A leak is rarely felt in the first minute. The signs: the longer the app is used, the slower it gets. The tab's memory use keeps rising, and in the end the tab can crash. The heap is the part of memory where JavaScript keeps objects, arrays and DOM elements. If you draw heap use as a graph over time, it has one of three shapes:
- Healthy: memory rises while the page works, then drops when the garbage collector (GC: the part of the browser that throws away data nothing holds any more) runs. The graph looks like the teeth of a saw.
- Leaking: every time the same action is repeated, memory rises and never goes back down to where it started. The graph looks like a staircase.
- Not a leak: a short spike that drops again once the page has loaded. Or memory that is big from the start but stays steady.
The first tool to confirm a leak is Chrome's Task Manager, a list of Chrome's tabs with the memory each tab uses. On Windows and Linux, press Shift+Esc. On a Mac, open the Window menu, then Task Manager. Right-click any column title, then turn on the JavaScript memory column. After that, use the page for a few minutes. If the number keeps rising, move on to the Memory tab in DevTools.
Three snapshots in the Memory tab
A heap snapshot is a picture of every object on the heap at one moment. Taking a snapshot always runs the GC first. So only objects that are still held get recorded.
- Open the page in an Incognito window, so browser extensions don't get recorded too.
- In DevTools, click the Memory tab, choose Heap snapshot, then click Take snapshot. This first snapshot is the baseline (the starting number you compare with).
- Do the suspect action a few times, for example open and close the Notifications panel 5 times. Then take a second snapshot.
- Repeat the action, then take a third snapshot.
- Pick the last snapshot. Switch its view from Summary to Comparison (the view that compares two snapshots), and compare it with the snapshot before.
This is the Comparison in this page's Lab, after the panel was opened and closed 6 times between snapshots 2 and 3:
| Class | # New | # Deleted | # Delta | Size Delta |
|---|---|---|---|---|
Array |
6 | 0 | +6 | +6 MB |
Detached <ul> |
6 | 0 | +6 | +1.2 kB |
Detached <li> |
300 | 0 | +300 | +30 kB |
- # New and # Deleted: how many objects of each class (the kind of object in the Class column) were created and thrown away between the two snapshots. # Delta is the difference, and Size Delta is the difference in size.
- The panel was closed 6 times, and exactly 6
<ul>were never thrown away. A number equal to how many times you did the action is the strongest sign of a leak. - Without a leak, # New and # Deleted are equal, and # Delta is 0.
Detached nodes and Retainers
A detached DOM node is an element that has been taken out of the page, for example with remove(). But JavaScript still holds a reference to it, so the GC can't throw it away. To list only detached nodes, type Detached into the Class filter box at the top of the snapshot view. Click one of the rows, and the Retainers section at the bottom shows the chain of references that holds it, up to a variable in your code. In the code below, the chain ends at the closedPanels array:
const closedPanels = [];
function closePanel(panel) {
panel.remove(); // out of the page...
closedPanels.push(panel); // ...but still held by the array: now it's detached
}
function closePanelFixed(panel) {
panel.remove();
closedPanels.push(panel.dataset.id); // keep just its id, the element can go
}
panel.remove()only takes the element out of the page. The element can only be thrown away once no variable, array or closure keeps it any more.closedPanels.push(panel)keeps the element, along with the 50<li>inside it and the data it holds. So one whole panel stays held in memory.- A heap snapshot shows two sizes for each object. Shallow size: the size of the object itself. Retained size: the memory that is freed along with it if that object is thrown away. The
<ul>in the Lab has a shallow size of about 200 bytes, but a retained size of about 1 MB, because that<ul>also holds its 50<li>and their data. Sort the list by Retained size, so the objects that hold the most memory are at the top.
Reading the trend from the numbers
In the exercise, you turn a row of snapshots into one decision: leak or no leak. The rise is calculated step by step, from one snapshot to the next. A leak means rising at every step: a single step without a rise (a drop, or no change) already means no leak. growthRate is the average rise, rounded to a whole number. severity (how serious it is) is "none" when nothing leaks, "low" when growthRate is below 5, and "high" when it is 5 or more. The detectLeaks function below follows that rule. Each snapshot is an object with heapUsed (the size of the heap):
function detectLeaks(memorySnapshots) {
if (memorySnapshots.length < 2) return { hasLeak: false, growthRate: 0, severity: "none" };
let keepsRising = true;
let total = 0;
for (let i = 1; i < memorySnapshots.length; i++) {
const delta = memorySnapshots[i].heapUsed - memorySnapshots[i - 1].heapUsed;
if (delta <= 0) keepsRising = false; // one step without a rise cancels the trend
total += delta;
}
const growthRate = Math.round(total / (memorySnapshots.length - 1));
if (!keepsRising) return { hasLeak: false, growthRate, severity: "none" };
return { hasLeak: true, growthRate, severity: growthRate < 5 ? "low" : "high" };
}
| Heap (MB) | Rises | Always rising? | growthRate |
Result |
|---|---|---|---|---|
| 10, 15, 21, 28 | 5, 6, 7 | yes | 18 / 3 = 6 | hasLeak: true, "high" |
| 10, 12, 14 | 2, 2 | yes | 4 / 2 = 2 | hasLeak: true, "low" |
| 10, 30, 25, 40 | 20, -5, 15 | no | 30 / 3 = 10 | hasLeak: false, "none" |
The last row is not a leak by this rule. The average rise is 10 MB, but there is one drop (30 to 25), so the trend isn't consistent. In the Lab, take a baseline snapshot first. Then open and close the panel 5 times and take a snapshot, 6 times and take a snapshot, 7 times and take a snapshot. The heap is exactly 10, 15, 21, 28 MB, like the first row.
The exercise's second function, findRetainedObjects, keeps the objects whose retainCount (the number of references holding the object) is more than 1. Then it returns just their names: objects.filter((o) => o.retainCount > 1).map((o) => o.name). From EventListener (3), DOMNode (1) and Timer (2), the result is EventListener,Timer. This rule is simplified for the exercise. In a real heap snapshot, an object held by a single reference is retained just the same. What makes it a leak is this question: should the code have released that reference already?
💡 Other tools in the Memory tab
- Allocations on timeline: records allocations (memory taken for new objects) while you use the page. Blue bars that are still there when the recording ends are objects that were never thrown away. The position of a bar shows at which second the object was created.
- Allocation sampling: records allocations by taking a sample now and then, not every one. So it adds little load to the page and suits long recordings. The results are grouped by the JavaScript function that created the objects.
- Detached elements (in newer Chrome versions): lists the detached elements still held by JavaScript right away, with no need to filter a snapshot.
⚠️ When the numbers fool you
- Concluding from one rise. A bigger second snapshot can be just a cache or data loaded once. Repeat the action and take three snapshots.
- Trusting the average. In the exercise,
10, 30, 25, 40rises on average, but one drop makes the resulthasLeak: falseand"none". Checkdelta <= 0at every step. - The wrong severity limit. In the exercise, a
growthRateof exactly 5 is already"high". UsegrowthRate < 5 ? "low" : "high". - Measuring with extensions on. Extensions put objects on the heap too and make the comparison unreliable. Use an Incognito window.
TL;DR: A memory leak is memory that is allocated (taken to store data) but never freed, because something still holds it. The sign is memory that keeps rising and an app that gets slower over time. Confirm it first in Chrome's Task Manager (Shift+Esc), which shows the memory of each tab. Then take three heap snapshots (pictures of every object on the heap, the memory where JavaScript keeps data) in the DevTools Memory tab: a baseline, one after repeating the action you suspect, and one after repeating it again. Compare them in the Comparison view. A class (kind of object) whose # Delta (the change in its count) equals the number of times you did the action is the suspect. Type Detached into the Class filter (the filter box) to find elements that were removed from the page but are still held by JavaScript. Then follow the Retainers section (the chain of references holding an object) to the variable. In the exercise, a leak means the heap rises at every snapshot. growthRate is the rounded average rise, and severity (how serious it is) is "none", "low" (below 5) or "high" (5 and up).
⚡ It keeps rising, not rising once
Meaning: A memory leak is memory that is allocated (taken to store data) but never freed, because something still holds it. The memory graph looks like a staircase: every time the same action is repeated, memory rises and never goes back down. Confirm it first in Chrome's Task Manager (Shift+Esc), which shows the memory of each tab. Then move on to the Memory tab in DevTools.
⚡ Three heap snapshots
Meaning: A heap snapshot is a picture of every object on the heap (the memory where JavaScript keeps data) at one moment. Take a baseline snapshot, repeat the action you suspect a few times, then take a second snapshot. Repeat it again, then take a third. Pick the Comparison view, which shows the difference between two snapshots. A class (kind of object) whose # Delta (the change in its count) equals the number of times you did the action is the suspect. For example, 6 new <ul> after a panel was closed 6 times.
⚡ Detached: out of the page, still held
Write:
function closePanel(panel) {
panel.remove(); // out of the page...
closedPanels.push(panel); // ...but still held by the array: now it's detached
}
Guess first: closedPanels is an array. After panel.remove(), is the panel element thrown out of memory?
Not yet. remove() only takes it out of the page. While the closedPanels array still holds it, the garbage collector (the part of the browser that throws away data nothing holds any more) can't throw it away.
Meaning: An element that is out of the page but still held by JavaScript is called a detached node. To find one, type Detached into the heap snapshot's Class filter (the filter box). Then follow the Retainers section (the chain of references holding the element) to its variable. The fix: keep just the panel's id (panel.dataset.id), not the element.
⚡ A leak means rising at every step
Guess first: a heap of 10, 30, 25, 40 MB in four snapshots. The average rises. Is it a leak?
Not by the exercise's rule. There's one drop (30 to 25), so the trend isn't consistent: the result is hasLeak: false (no leak).
Meaning: Calculate the rise from snapshot to snapshot. One step without a rise (a drop or no change) already means no leak.