So, now that I’ve refreshed your memory on the upside of console.log over a breakpoint, let’s talk about the downside compared to breakpoints. To add a console.log statement, you have to edit the source code of your application. And editing the source code of your application is an even bigger break in your debugging workflow. You have to go back to the editor, add the log statement, refresh the page, and then go back to where you were. And don’t forget to remove that log statement before you commit your source code.
Well what if you could avoid those limitations?
- What if you could dynamically add/remove console.log statements to an application running in a web browser?
- What if when you added those console.log statements you didn’t have to worry about committing them to source control?
- What if you could add console.log statements to any code in a web application, even code like JQuery or Angular or some other third-party code?
- What if you could dynamically add/remove console.log statements in browsers all the way to IE8?
You can. Just follow these three simple steps:
- Add a breakpoint where you’d like your console.log statement to be
- Right-click on the breakpoint to set the condition of the breakpoint
- In the dialog that comes up set the expression as console.log(‘message’). If you want detail about a variable just include that in your expression, something like console.log(‘name is ‘ + name + ‘ age is ‘ + age). Or you could do something like console.log(‘complicated obj is ‘ + JSON.stringify(obj));
That’s all you need to do.
I have some screenshots showing the right-click menu and the dialog that comes up for a variety of browsers. If you scroll down further, I’ll quickly explain why it works.
So, how does it work?
Well, we are using conditional breakpoints, which is a feature found in quite a few debuggers, such as Visual Studio, Eclipse and Python. When the conditional expression is true, the debugger stops at the breakpoint. When the conditional expression is false, the debugger still executes the expression but will not stop at the breakpoint.