As you might already know, your browser’s developer tools can be used to debug JavaScript by utilizing breakpoints. Breakpoints allow you to pause script execution as well as step into, out of, and over function calls. Breakpoints are added in your developer tools by means of line numbers where you indicate where you want script execution to be paused.
This is fine until you start changing your code. Now a defined breakpoint may no longer be in the place you want it to be. Take the following code as an example:
function doSomething() {
console.log('first log...');
console.log('last log...');
}
doSomething();
If I open this code in my browser’s developer tools debugger, I can place a breakpoint before one of the lines inside the doSomething()
function. Let’s say I want to pause script execution before the “last log…” message. This would require that I place the breakpoint on that line. In this case, it would be line 3 of my code.
But what if I add the breakpoint, then I add another line of code before that line?
function doSomething() {
console.log('first log...');
console.log('second log...');
console.log('last log...');
}
doSomething();
If I refresh the page, the breakpoint will still be there but now the script will pause execution on the “second log…” message instead of the “last log…” message. Again, this is because the breakpoints are based on line numbers. The debugger is still stopping on line 3, but that’s not what we want.
Enter JavaScript’s debugger
statement.
Instead of setting breakpoints directly in the developer tools, I can use the debugger
statement to tell the developer tools where to pause execution:
function doSomething() {
console.log('first log...');
debugger;
console.log('last log...');
}
doSomething();
Now I can add as much code as I want prior to the debugger
statement and the script will still pause in the right place, without any concerns over changing line numbers.
If you’ve been writing JavaScript for a while, I’m sure this tip is nothing new to you. But those new to debugging will certainly benefit from using this feature, which is part of the official ECMAScript spec. As expected, inserting a debugger
statement will have no effect on your code if a debugger is not present (e.g. if the developer tools are not open).