Javascript Debugging Trick: Log Without Modifying Code

In Technical Brief by Chris Strahorn

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

Step 1

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

Step 2

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

Step 2.5
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

Step 3
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.

Result

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 a leader in marketing technology and site optimization solutions. More than prioritizing and executing industry leading CRO practices, we do what makes the money; optimizing our Client’s digital commerce product toward consistent financial growth and ROI. All achieved through excellence in Lean UX, Analytics, Research, Experimentation and Development.
Contact Mobile1st Experts Now!