Explain Codes LogoExplain Codes Logo

How to set a JavaScript breakpoint from code in Chrome?

javascript
debugging
breakpoints
javascript-debugging
Nikita BarsukovbyNikita Barsukov·Feb 21, 2025
TLDR

To halt JavaScript execution in Chrome, insert debugger; where you need a breakpoint. Chrome DevTools must be active for this line to function, behaving just like a standard breakpoint.

Example:

// Nothing to see here, moving along... // Just kidding, the code execution stops here if DevTools is open debugger;

Need for debugger;

In complex flows or when code is hard to reach via the UI, it's efficient to automatically halt the code for thorough inspection. That's what debugger; brings to the table. It enables you to pause and see the state of your application at that exact line of code.

debugger; Best Practices

Although using debugger; is rather simplistic, be mindfully cautious of the following:

  • It's a no-show if DevTools is not open.
  • It could cause unnecessary halts in production if left in code.
  • Always wrap debugger; statements in development-only checks.

Programmatic Conditional Breakpoints

Why stick to static debugger; statements when you can be dynamic? Set conditional breakpoints like so:

if (totalOrders > expectedOrders) { // Only stop here if our order expectations are exceeded debugger; // "Ah, so we're popular today!" 🎉 }

Deep dive with debugger

While debugger; works like a charm for most use-cases, there may be times you'd want to dynamically set breakpoints from the console. Chrome's <code>debug(function)</code> is here to rescue, find out more in the Command Line API.

Want to make your debugging interactive? Bind debugger; to event listeners:

document.querySelector('.suspicious-button').addEventListener('click', function() { debugger; // Breakpoint on button click // "This button has been acting shady lately!" 🕵️‍♂️ });

Good news! The use of debugger; is standardized in ES5 and later, ensuring cross-browser compatibility.

Not just for browsers

Guess what? Node.js is also your playground for debugger;. You can halt execution in a Node.js app just like in a browser, truly universal across JavaScript environments.