Site icon JavaScript Artisan

The `debugger` statement

Comic by XKCD on debugging

Debugging. It’s something that every coder does frequently. It takes far more time than creating new code, feels less useful, and can be exceedingly frustrating. Sometimes it’s a s simple as changing a label typo, and other times it feels like trying to escape the labyrinth of the Minotaur while blindfolded. Yet it is a fundamental part of the software creation process. We all create bugs, so we must all learn to fix them as efficiently as possible. A certain amount of debugging ability comes from skill and learned experience, and the rest lies in the quality of our tools.

The most basic and powerful tool for debugging is… the debugger. (It’d be cooler if it was called the transmogrifier or something, right?) The transmog… um, debugger, allows you to step through each line of code as it is executed, inspect the value of any variables that are in scope, and generally answer the question, “is this code actually doing what I think it’s doing?” (Spoiler alert: nope!) The ability to see the internal state of the invisible machine that is your code is tremendously helpful in the task of figuring out why it’s not working. It can back you down from the ledge of keyboardSMASH, to a calmer, more collected debugging experience.

Using the debugger takes some practice, but the most basic action is called a breakpoint. A breakpoint is simply a line of your code where execution stops so you can look at what’s happening. From there, you can step through lines one-by-one to see data handling and execution steps to figure out what’s going wrong. Setting a breakpoint is as simple as clicking on the line number in the Chrome debugger, but sometimes, especially if you’re using transpilation, you don’t know exactly where the line is in the final source. Enter the debugger statement. When you want to stop execution at a certain point in your code, just use the plain keyword debugger;(remember the semicolon) and the debugger will trigger a breakpoint right there. If there’s no dubugger present, the statement will be ignored. As a good practice, you should have ESLint flag a debugger statement as an error so it doesn’t accidentally go out to production! Good luck and happy (or at least non-enraged) debugging.

Exit mobile version