Debugging JavaScript with the debugger statement

January 5, 2017

One of the most useful statements in JavaScript is debugger. It invokes any available debugging functionality from your application and has no effect if there is no functionality available.

So, for example if you have some JavaScript running and you want to pause execution at a certain line you can do something like:

function foo() {
  debugger; // will open devtools if executed in the browser or a node debugger if available

Most of the time, if you are working with browser JavaScript, adding a debugger; line is equivalent to setting a breakpoint in the sources tab of your developer tools. For example in Chrome you could just:

Because it can be accessed either way, I find debugger to be most useful in 3 situations.

  1. When you don’t have control over the browser. For example if you are running automated tests and can’t click through to add a breakpoint adding a debugger; line in your test will do the trick!
  2. If you are not in a browser environment.
  3. If your code is minified/concatendated making it difficult to find from the browser.