Debugging with DevTools
Debugging is the process of finding out why a program doesn't do what you expect, and fixing it. The two main tools are the console, for printing values while the program runs, and the debugger, which pauses the program at a line you choose so you can inspect every variable and step through the code one line at a time. Every browser includes both in its developer tools (DevTools), and Node.js connects to the same tools. Learning them turns guessing into looking.
In One Minute
- Read the error first: its type, message and the first line of the stack trace usually point straight at the problem.
console.logis fine;console.table,console.group,console.time,console.assertandconsole.traceshow more with less effort.- A breakpoint pauses the program at a line. Then step over, step into and step out to follow it.
- The
debugger;statement acts as a breakpoint written in code (when DevTools is open). - Debug Node.js with
node --inspect file.jsand Chrome'schrome://inspect, or VS Code's debugger.
A Debugging Process
- Reproduce it. Find the exact input that causes the bug. A bug you can trigger on demand is half solved.
- Read the error. Type, message, file and line.
- Form a guess about the cause ("the balance is a string, not a number").
- Check the guess with a log or a breakpoint, by looking at the actual values.
- Fix it, then confirm with the same input, and ideally add a test (next lesson) so it can't come back.
Reading a Stack Trace
When an error isn't caught, the console shows its stack trace: the chain of function calls that led to it, innermost first.
TypeError: Cannot read properties of undefined (reading 'toFixed')
at formatUsd (app.js:2:17)
at billLine (app.js:6:24)
at app.js:10:13Read it top down: the error happened in formatUsd at line 2, column 17, which was called from billLine at line 6, which was called from the top level of app.js at line 10. The message says something passed to formatUsd was undefined, so look at what billLine passed on line 6. In DevTools, each file:line is a clickable link to the source.
Console Methods
| Method | Description |
|---|---|
console.log(...values) | It is used to print values. |
console.error(...) / console.warn(...) | It is used to print messages styled as errors or warnings (and filterable). |
console.table(data) | It is used to print an array of objects (or an object) as a table. |
console.group(label) / console.groupEnd() | It is used to indent related messages together. |
console.time(label) / console.timeEnd(label) | It is used to measure how long code takes. |
console.count(label) | It is used to count how many times a line runs. |
console.assert(condition, ...msg) | It is used to print an error only when the condition is false. |
console.trace(...msg) | It is used to print the current stack trace without throwing. |
console.dir(obj, { depth }) | It is used to print an object's properties, expanding nested levels. |
These examples run with Node.js's own console (Try it's console shows only log, info, warn and error), so the output looks the way it does in a terminal. Browser DevTools shows the same information interactively.
console.table
const payments = [
{ name: "Navika", amount: 120, paid: true },
{ name: "Srihitha", amount: 85, paid: false },
{ name: "Advitha", amount: 45, paid: true },
];
console.table(payments);
console.table(payments, ["name", "amount"]);┌─────────┬────────────┬────────┬───────┐
│ (index) │ name │ amount │ paid │
├─────────┼────────────┼────────┼───────┤
│ 0 │ 'Navika' │ 120 │ true │
│ 1 │ 'Srihitha' │ 85 │ false │
│ 2 │ 'Advitha' │ 45 │ true │
└─────────┴────────────┴────────┴───────┘
┌─────────┬────────────┬────────┐
│ (index) │ name │ amount │
├─────────┼────────────┼────────┤
│ 0 │ 'Navika' │ 120 │
│ 1 │ 'Srihitha' │ 85 │
│ 2 │ 'Advitha' │ 45 │
└─────────┴────────────┴────────┘A list of objects is far easier to scan as a table than as nested braces. The second argument picks columns.
group and count
function lateFee(student) {
console.group(`lateFee(${student.name})`);
console.count("lateFee calls");
console.log("daysLate:", student.daysLate);
const fee = Math.max(student.daysLate - 10, 0) * 2;
console.log("fee:", fee);
console.groupEnd();
return fee;
}
lateFee({ name: "Navika", daysLate: 14 });
lateFee({ name: "Advitha", daysLate: -3 });lateFee(Navika)
lateFee calls: 1
daysLate: 14
fee: 8
lateFee(Advitha)
lateFee calls: 2
daysLate: -3
fee: 0Grouping keeps the log lines of each call together, and the counter shows at a glance how often the function ran. The negative daysLate is a bug in the input data; console.assert(student.daysLate >= 0, "...") would flag it, printing a message only when the condition is false (the next lesson shows it).
Timing Code
console.time("sum a million fees");
let total = 0;
for (let i = 0; i < 1_000_000; i++) total += i % 500;
console.timeEnd("sum a million fees");sum a million fees: 4.012msThe time differs on every run and every machine, so this example's output isn't compared when the lesson is checked. For serious measurement, use performance.now() and repeat the work many times (see the performance lesson).
Breakpoints and Stepping
Logging requires guessing what to print and re-running. A breakpoint pauses execution at a line so you can see everything at that moment.
In Chrome or Edge DevTools, open the Sources panel (Firefox: Debugger), open your file, and click a line number. Reload or trigger the code; execution stops at that line, and the panel shows:
| Panel | Shows |
|---|---|
| Scope | Every variable visible at this line: local, closure, module and global, with current values |
| Call Stack | The chain of calls that led here; click a frame to inspect it |
| Watch | Expressions you add (such as student.balance * 2), re-evaluated at each step |
| Breakpoints | All your breakpoints, with checkboxes to disable them |
Then control execution with the toolbar (or keys):
| Button | Key (Chrome) | Does |
|---|---|---|
| Resume | F8 | Run until the next breakpoint |
| Step over | F10 | Run this line, stop at the next (don't go inside functions) |
| Step into | F11 | Go inside the function called on this line |
| Step out | Shift+F11 | Finish this function, stop in its caller |
Hovering over any variable in the source while paused shows its value. The Console panel also works while paused, in the current scope, so you can type student.fees.length to check something on the spot.
Special Breakpoints
| Type | How | Use for |
|---|---|---|
| Conditional | Right-click a line number, "Add conditional breakpoint", enter student.name === "Advitha" | Stopping only for the case that fails |
| Logpoint | Right-click, "Add logpoint", enter "fee", fee | Logging without editing the code |
| Exception | Sources panel, "Pause on exceptions" | Stopping exactly where an error is thrown |
| DOM change | Elements panel, right-click an element, "Break on" | Finding which code changes the page |
| Event listener | Sources panel, "Event Listener Breakpoints", such as "click" | Finding which code handles an event |
The debugger Statement
Writing debugger; in your code pauses there whenever DevTools (or another debugger) is open, as if you had set a breakpoint. When no debugger is attached, it does nothing:
function applyDiscount(fee, code) {
if (code === "STAFF") {
debugger; // pauses here when DevTools is open
}
return fee * 0.5;
}It is handy in code that is hard to find in the Sources panel, such as code generated by a build tool. Remove it before committing; linters flag it (no-debugger).
Debugging Node.js
Node.js speaks the same debugging protocol as Chrome:
node --inspect-brk app.js--inspect-brk starts the program paused on its first line and prints a ws:// address. Open chrome://inspect in Chrome, click inspect under your script, and you get the full DevTools debugger for Node.js. Use --inspect (without -brk) for servers that should start running immediately.
In VS Code, open the file, set breakpoints by clicking left of the line numbers, and press F5 (choose "Node.js"). VS Code's JavaScript Debug Terminal auto-attaches the debugger to any node command you run in it, so node app.js stops at your breakpoints with no flags.
In Practice
A Fee Tracker bug: the total is "0120855" instead of 250. A well-placed console.table and a type check show the cause in one run:
const rows = [{ amount: "120" }, { amount: 85 }, { amount: "45" }];
console.table(rows.map((r) => ({ amount: r.amount, type: typeof r.amount })));
const broken = rows.reduce((sum, r) => sum + r.amount, 0);
const fixed = rows.reduce((sum, r) => sum + Number(r.amount), 0);
console.log({ broken, fixed });┌─────────┬────────┬──────────┐
│ (index) │ amount │ type │
├─────────┼────────┼──────────┤
│ 0 │ '120' │ 'string' │
│ 1 │ 85 │ 'number' │
│ 2 │ '45' │ 'string' │
└─────────┴────────┴──────────┘
{ broken: '01208545', fixed: 250 }The table makes the mixed types obvious: two amounts arrived as strings, so + joined them. The fix converts each amount; the better fix converts at the point where the data enters the program.
Common Mistakes
Not reading the error message. The type, message and line number usually say exactly what's wrong.
Logging objects and reading them later. In the browser console, an object you expand later shows its current contents, not its contents when logged. Log specific values, or JSON.stringify a snapshot.
Leaving console.log and debugger in production code. Remove them, or use a linter rule to catch them.
Changing code randomly until it works. Form a guess and check it with real values; random changes create new bugs.
Practice
Challenge: This function should return the average payment but returns NaN for the data below. Add one console.log (or console.table) to find the bad value, then fix the function so it skips amounts that aren't numbers.
function average(payments) {
const total = payments.reduce((sum, p) => sum + p.amount, 0);
return total / payments.length;
}
console.log(average([{ amount: 120 }, { amount: undefined }, { amount: 60 }]));Show solution
function average(payments) {
const valid = payments.filter((p) => Number.isFinite(p.amount));
const total = valid.reduce((sum, p) => sum + p.amount, 0);
return total / valid.length;
}
console.log(average([{ amount: 120 }, { amount: undefined }, { amount: 60 }]));90Key Takeaways
| Tool | Use |
|---|---|
console.table(rows) | Inspect a list of objects |
console.assert(cond, msg) | Flag broken assumptions |
| Breakpoint | Pause and inspect everything |
| Conditional breakpoint | Pause only for the failing case |
| Pause on exceptions | Stop at the throwing line |
node --inspect-brk app.js | Debug a Node.js script |
Was this tutorial helpful?