JS Tip of the Day: The debugger Statement

The debugger Statement
Level: Intermediate

Code doesn’t always work the way it should and sometimes you need to step through the code line by line to figure out what’s going wrong. Debuggers provide this ability, allowing you to set breakpoints in your code that will cause it to pause mid-execution. Then you can inspect the current values of variables, check out the call stack, and do all kinds of things to help you diagnose the problem.

Depending on your tooling and the configuration of your environment, you may or may not be able to set breakpoints directly within your code editor. If not, you might find the debugger statement handy. When encountered in running code the debugger statement will trigger the debugger (if available) just like a breakpoint would if it were enabled for the line in which it was placed.

let x = 1;
console.log('x is', x); // x is 1
debugger; // (Debugger pauses on this line)
console.log('y is', y); // ...

This code will trigger the debugger where the debugger statement is, right before reaching the second console.log() call. A developer may then be able to see that the next line, before it even runs, will cause a ReferenceError because a y variable has yet to be defined (though you could probably guess that one without the debugger too).

Note: for the debugger to catch in a browser, you may need to make sure you have the developer tools open.

More info:


More tips: JavaScript Tips of the Day

2 Likes