Javascript Debugging Trick: Log Without Modifying Code

One of the first debugging techniques most developers learn is to add log statements to track the flow of an application. In Javascript, this task is accomplished with console.log(). Logging is quickly abandoned for debugging with breakpoints because it can give you far more information and doesn’t require extra code that should be cleaned up later. Yet there are some instances where you wouldn’t want to break application flow with breakpoints, such as during dragging or animations. In those cases, logging can be the best choice to gain insight into what’s happening without stopping the action.

But what if I told you there was a better way to do Javascript debugging: a way to log without leaving log statements to be cleaned up later or, worse, to be forgotten. Being able to edit breakpoints gives us a secret way to do logging without having to modify the code.

Step 1: Put a regular breakpoint where you want to log

This part is pretty easy. If you’re not experienced with breakpoints, you click on the line number in the Chrome debugger where you want to have your breakpoint.

Step 2: Edit the breakpoint

To edit a breakpoint, right click on the breakpoint and select edit breakpoint.

This brings up a text field used for conditional breakpoints (only break when x.name === “joe” for example). It’ll only break when the condition is true.

Step 3: Put the logging in the breakpoint

Now all that’s left is to put your actual log in the breakpoint. Just put in your message and it’ll show up in the console but the breakpoint won’t be activated.

How it works

So, remember edited breakpoints only stop when the expression is true. This tells us two things: the debugger executes that code each time the breakpoint would be hit and if the expression returns false the breakpoint doesn’t stop. console.log() returns undefined and undefined is falsy (find out more about truthy and falsy) so the code gets run but the breakpoint doesn’t get triggered.

Mobile1st is the company behind Mobilizer, the mobile optimization platform. Mobilizer helps companies increase revenue and engagement by enabling them to see exactly what their mobile users see, quickly identify display issues, monitor metrics by device, and optimize the mobile customer experience.