Back to results for “UI Testing”
Node.js › Debugging & Diagnostics

How do you use the built-in 'debugger' statement together with Node's --inspect flag to set breakpoints in code?

Beginner

Answer

Placing a 'debugger;' statement directly in code creates a programmatic breakpoint -- when the script is run with 'node --inspect-brk' and a debugger client (Chrome DevTools or VS Code) is attached, execution pauses at that exact line, letting you inspect variable values, step through subsequent lines one at a time, and evaluate expressions in the current scope before resuming.
function calculateTotal(items) {
  debugger; // execution pauses here when run with --inspect-brk and a debugger attached
  return items.reduce((sum, item) => sum + item.price, 0);
}

// node --inspect-brk app.js, then open chrome://inspect
Real-world example A developer debugging an incorrect total calculation adds a 'debugger;' statement right before the reduce() call, runs the script with --inspect-brk, and steps through each iteration in Chrome DevTools to discover one item's price was unexpectedly undefined rather than a number.

Common follow-ups: What's the difference between --inspect and --inspect-brk in terms of when execution first pauses?;How would you achieve the same breakpoint without modifying the source code, using DevTools' own breakpoint UI instead?