Using ‘debugger’ to help in javascript debugging

When you’re working on javascript code, you can set a breakpoint from your editor by putting in the statement ‘debugger;’ in your code where you want to break. It’s better in many cases than manually setting a breakpoint in the inspector.

I recently was working with a very talented front-end engineer who had never seen this trick, and so wanted to share it with the subset of javascript engineers out there who for whatever reason have never seen this. Put it in your code where you want to break, open up the web inspector, and the code will stop where you commanded, allowing you to walk the code forward, inspect the stack, and get and set local variables at will.

(function(){
   var time = +new Date;
   //no idea what that did, let's check it out
   debugger;
   //You can now modify local variables as well
   alert(time);
})();

Pro Tip: ‘debugger’ statements cannot be disabled at runtime, so don’t put ‘debugger’ inside of a loop. Instead put it right before the loop and then manually set a breakpoint in the web inspector. That way once you’ve found out what you need inside the loop, you can disable the manual breakpoint and the rest of the iterations will continue without you having to mash F8.

Discussion on HackerNews

Read More →