Debugging with DevTools

Updated · 10 min read
mediumES2026javascriptdebuggingdevtoolsconsolebreakpoints

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.log is fine; console.table, console.group, console.time, console.assert and console.trace show 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.js and Chrome's chrome://inspect, or VS Code's debugger.

A Debugging Process

  1. Reproduce it. Find the exact input that causes the bug. A bug you can trigger on demand is half solved.
  2. Read the error. Type, message, file and line.
  3. Form a guess about the cause ("the balance is a string, not a number").
  4. Check the guess with a log or a breakpoint, by looking at the actual values.
  5. 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.

Console
TypeError: Cannot read properties of undefined (reading 'toFixed')
    at formatUsd (app.js:2:17)
    at billLine (app.js:6:24)
    at app.js:10:13

Read 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

MethodDescription
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

table.js▶ Try it
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"]);
Output
┌─────────┬────────────┬────────┬───────┐
│ (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

group.js▶ Try it
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 });
Output
lateFee(Navika)
  lateFee calls: 1
  daysLate: 14
  fee: 8
lateFee(Advitha)
  lateFee calls: 2
  daysLate: -3
  fee: 0

Grouping 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

time.js▶ Try it
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");
Output
sum a million fees: 4.012ms

The 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:

PanelShows
ScopeEvery variable visible at this line: local, closure, module and global, with current values
Call StackThe chain of calls that led here; click a frame to inspect it
WatchExpressions you add (such as student.balance * 2), re-evaluated at each step
BreakpointsAll your breakpoints, with checkboxes to disable them

Then control execution with the toolbar (or keys):

ButtonKey (Chrome)Does
ResumeF8Run until the next breakpoint
Step overF10Run this line, stop at the next (don't go inside functions)
Step intoF11Go inside the function called on this line
Step outShift+F11Finish 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

TypeHowUse for
ConditionalRight-click a line number, "Add conditional breakpoint", enter student.name === "Advitha"Stopping only for the case that fails
LogpointRight-click, "Add logpoint", enter "fee", feeLogging without editing the code
ExceptionSources panel, "Pause on exceptions"Stopping exactly where an error is thrown
DOM changeElements panel, right-click an element, "Break on"Finding which code changes the page
Event listenerSources 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:

debugger-statement.js
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:

Terminal
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:

bug.js▶ Try it
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 });
Output
┌─────────┬────────┬──────────┐
│ (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.

practice.js
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
practice-solution.js▶ Try it
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 }]));
Output
90

Quick check: Debugging

3 questions
1Which line of a stack trace shows where the error was thrown?
2What does "step over" do while paused at a breakpoint?
3Which console method prints a message only when a condition is false?

Key Takeaways

ToolUse
console.table(rows)Inspect a list of objects
console.assert(cond, msg)Flag broken assumptions
BreakpointPause and inspect everything
Conditional breakpointPause only for the failing case
Pause on exceptionsStop at the throwing line
node --inspect-brk app.jsDebug a Node.js script

Was this tutorial helpful?

Lesson 62 of 139