Sub topic 5
Debugging JavaScript with breakpoints
This chapter assumes you can read basic JavaScript, including functions, loops and async/await. It also assumes you know how to open DevTools and have used the Console. The panel names here follow Chrome and other Chromium browsers. Firefox calls the equivalent panel Debugger, and Safari puts it under Sources.
Why breakpoints beat `console.log`
Logging answers one question per page reload. You add a line, reload, read the output, then add another line. A breakpoint pauses the program at a chosen point. While it is paused you can read every variable in scope, walk up the call stack, and run any expression in the Console against the paused state. Then you can step forward one statement at a time.
The cost is a small amount of setup. You need to know where to pause and which kind of breakpoint to use. Most of this chapter is about that choice.
The Sources panel layout
The Sources panel has three areas.
- Navigator (left): the files the page loaded, grouped by origin. Use Ctrl+P (Cmd+P on macOS) to open a file by name.
- Editor (center): the selected file. Click a line number to set a breakpoint on that line.
- Debugger sidebar (right): the controls and state panes. Its main panes are Breakpoints, Watch, Call Stack and Scope.
When execution pauses, the editor highlights the line that is about to run. That line has not executed yet.
A worked example
Save this as cart.html and open it in the browser. It has a bug: the total comes out wrong.
<!DOCTYPE html>
<html>
<body>
<script>
function parsePrice(text) {
return parseFloat(text.replace('$', ''));
}
function cartTotal(items) {
let total = 0;
for (const item of items) {
total += parsePrice(item.price) * item.qty;
}
return total;
}
const items = [
{ name: 'Pen', price: '$1.50', qty: 2 },
{ name: 'Book', price: '$12.00', qty: 1 },
{ name: 'Bag', price: '$1,200.00', qty: 1 }
];
console.log(cartTotal(items));
</script>
</body>
</html>The Console prints 16. The expected total is 1215. Debug it in these steps.
- Open DevTools, go to Sources, and select
cart.html. - Click the line number next to
total += parsePrice(...). A blue marker appears. - Reload the page. Execution pauses on the first loop iteration.
- Look at the Scope pane.
itemis the Pen,totalis0. - Press F8 to resume. The loop pauses again with the Book. Press F8 once more to reach the Bag.
- On the Bag iteration, press F11 to step into
parsePrice. Selecttext.replace('$', '')in the editor, then evaluate it in the Console. It returns"1,200.00". - Evaluate
parseFloat("1,200.00")in the Console. It returns1.parseFloatstops reading at the comma.
The fix is to strip commas as well as the dollar sign.
function parsePrice(text) {
return parseFloat(text.replace(/[$,]/g, ''));
}Pressing F8 repeatedly works for three items. It does not work for three thousand. The next section covers breakpoints that avoid that.
Kinds of breakpoints
| Type | How to set it | Use it when |
|---|---|---|
| Line | Click the line number | You know where the problem is |
| Conditional | Right-click the line number, choose Add conditional breakpoint | The code runs many times and only one case is wrong |
| Logpoint | Right-click the line number, choose Add logpoint | You want a log message without editing the source |
| `debugger` statement | Write `debugger;` in the code | You need the pause to survive edits and reloads, or the line is hard to find |
| Event listener | Sources sidebar, Event Listener Breakpoints | You don't know which code handles a click, keypress or timer |
| DOM change | Elements panel, right-click a node, Break on | Something changes an element and you don't know what |
| XHR/fetch | Sources sidebar, XHR/fetch Breakpoints | You want to pause when a request to a matching URL is sent |
| Exception | Pause on exceptions button | An error is thrown and you want the state at the throw |
Conditional breakpoints
A conditional breakpoint pauses only when its expression is truthy. In the cart example, set the condition to item.name === 'Bag'. The page pauses on the Bag iteration and skips the two items before it.
The expression is evaluated in the scope of that line. It can call functions, but those functions run on every hit, so keep them cheap. If the expression throws an error, DevTools treats the condition as true and pauses. This can look like the condition is being ignored.
Logpoints
A logpoint prints a value to the Console each time its line runs, and it never pauses. For the cart, a logpoint on the total += line with the expression item.name, item.price, item.qty prints one line per item. You get console.log output with no source edit and nothing to remove later. The logpoint lives in DevTools, not in your file.
The `debugger` statement
A debugger statement pauses execution when DevTools is open. When DevTools is closed it does nothing.
function applyDiscount(price, percent) {
const discount = price * percent / 100;
debugger; // execution pauses here when DevTools is open
return price - discount;
}
applyDiscount(80, 25);Use it for code that runs before you can click in the editor, such as a script that executes during page load. Remove it before shipping. A leftover debugger pauses the page for any user who opens DevTools.
Event listener and DOM change breakpoints
Suppose a button click does something unexpected and you can't find the handler in a large bundle. Open Event Listener Breakpoints, expand Mouse, and tick click. The next click pauses at the first line of the first listener that runs. The Call Stack pane then shows who called it.
For a DOM change breakpoint, right-click an element in the Elements panel and choose Break on. The options are subtree modifications, attribute modifications and node removal. Execution pauses on the JavaScript line that caused the change.
Pausing on exceptions
The Pause on exceptions button has two settings. By default it pauses on uncaught exceptions. A checkbox adds caught exceptions, which pause inside every try block that throws.
Turn on the caught setting only briefly. Many libraries throw and catch errors in normal operation, and you will stop in code you don't care about.
Choosing where to pause
Stepping through code
When paused, the toolbar at the top of the debugger sidebar gives you these controls. Shortcuts are the Chrome defaults on Windows and Linux. On macOS, use Cmd for Ctrl.
| Control | Shortcut | What it does |
|---|---|---|
| Resume | F8 | Runs until the next breakpoint or the end |
| Step over | F10 | Runs the current line. If it calls a function, runs the whole call without stopping inside |
| Step into | F11 | Enters the function called on the current line |
| Step out | Shift+F11 | Finishes the current function and pauses at the caller |
| Step | F9 | Runs one statement at a time, and also moves through `await` boundaries |
A common pattern is to use Step over to move along a function. When a line calls something suspicious, use Step into. When you realize you've entered code you don't care about, use Step out.
Step into can land in library code or browser internals. Right-click a file in the Navigator and choose Add script to ignore list. DevTools then skips that file when stepping and hides its frames in the Call Stack. This is also called blackboxing. Frameworks and bundled vendor code are the usual candidates.
Reading the paused state
Scope
The Scope pane lists variables grouped by where they live. Local holds the current function's variables, Closure holds variables captured from outer functions, and Global holds the window. Block scopes from let and const appear as their own groups.
Values are live. Double-click one to edit it, press Enter, and resume. The program continues with your value. This is a fast way to test a fix without editing the source.
Watch
The Watch pane keeps expressions that re-evaluate at every pause. Add total.toFixed(2) or items.length and you can see how they change as you step. Watch expressions that throw, for example because a variable is out of scope, show an error and do not stop the debugger.
Call stack
The Call Stack pane lists the active function calls, with the current one on top. Click a frame to see the code at that call site, and the Scope pane switches to that frame's variables. This answers the question of how the code ended up in this state.
The Console while paused
Anything you type in the Console runs in the scope of the selected frame. You can inspect item, call parsePrice('$5'), or test a corrected expression. The Console utilities from the previous chapter, such as copy(), work here too. For example, copy(JSON.stringify(items)) copies the paused data.
Debugging asynchronous code
In asynchronous code, the call stack at a pause often shows only a small part of the story. A callback that runs after a timer has no synchronous caller. DevTools helps by joining the stacks. Frames from earlier turns of the event loop appear in the Call Stack under a label such as await or setTimeout.
async function loadUser(id) {
const response = await fetch('/api/users/' + id);
const user = await response.json();
return user.name.toUpperCase();
}
async function showUser() {
const name = await loadUser(42);
document.title = name;
}
showUser();Put a breakpoint on the return line. If it pauses, the Call Stack shows loadUser on top and showUser below it, even though showUser first ran in an earlier turn. Pressing F10 on an await line steps over it and pauses on the next line once the promise resolves.
If user.name is missing, the .toUpperCase() call throws a TypeError. With Pause on exceptions enabled, the debugger stops there. You can inspect user in Scope and see the actual response shape.
Source maps and minified code
Production bundles are usually minified, with short names and one very long line. If the build produces source maps, DevTools loads them and shows your original files in the Navigator, often under a folder named for the bundler. Breakpoints set in the original files work. Variable names in the Scope pane are mapped back as well.
If you see only a minified file, check these things.
- The
.mapfile must be reachable. Look for a failed request in the Network panel. - The bundle must have a
sourceMappingURLcomment pointing to it. - The Enable JavaScript source maps setting in DevTools must be on.
As a fallback, click the {} Pretty-print button under the editor. It reformats the code with line breaks, although variable names stay short.
Common errors
- The breakpoint never hits. Check that the code actually runs. Add a logpoint and look for output. Make sure the file you opened is the same one the page loaded, not a stale copy cached by the browser or a different origin.
- The breakpoint hits, but the values are not what the source shows. You may be looking at a bundled file, or the page loaded an older build. Reload with the cache disabled, which is an option in the Network panel while DevTools is open.
- The breakpoint moved to a different line. On a line with no executable code, DevTools moves it to the nearest line that has some. Check the Breakpoints pane to see where it ended up.
- Everything pauses at once. A
debuggerstatement, a caught-exception setting or an event listener breakpoint is still active. Review the Breakpoints pane and untick or remove the ones you don't need. - Breakpoints are ignored. The Deactivate breakpoints button, or Ctrl+F8, turns all of them off without removing them. The icon turns blue when active.
- Stepping jumps into a library. Add the library to the ignore list, or use Step out.
- Pauses in code that isn't yours. Browser extensions run scripts in the page. Test in an incognito window or a profile with extensions disabled.
Exercise
In the cart example, the loop runs for 5,000 items and only the item with the name 'Bag' has a wrong price. Name two ways to inspect it without pressing F8 5,000 times, and say how they differ.
Show answer
Use a conditional breakpoint with the condition item.name === 'Bag'. It pauses once, on the item you care about, and you can inspect all scope variables and step from there. Alternatively, use a logpoint with item.name, item.price to print one Console line per iteration without pausing. The conditional breakpoint gives you an interactive stop. The logpoint gives you a record of every iteration but no ability to inspect or step.
Exercise
A click handler changes a button's text, but you can't find which script does it. Which breakpoint do you set, where, and what do you look at when it pauses?
Show answer
Right-click the button in the Elements panel and choose Break on, then subtree modifications (for text changes in children) or attribute modifications, depending on what changes. Trigger the action. Execution pauses on the JavaScript line that changed the element. Read the Call Stack pane to see the chain of calls that led to it.
Exercise
You are paused inside parsePrice and want to know how the code got there. Which pane do you use, and what happens to the Scope pane when you click a different frame?
Show answer
Use the Call Stack pane. Clicking a different frame shows the code at that call site, and the Scope pane switches to show the variables of that frame.