Debugging JavaScript can be a tedious process. Especially when debugging a function that is called many times in an application. There may be some kind of utility function in an app that processes data, but there’s a bug with one of the values.
In order to debug the function you’d open up Chrome or IE’s Dev Tools and throw in a breakpoint. If the function being debugged is used in many areas, you’ll have to hit continue multiple times to get to the specific case needed.
There are two different ways to avoid this problem.
Say you have the following code.
var process = function( obj ) { var type = Object.prototype.toString.call( obj ); return type; }; console.log( process({}) ); console.log( process([]) ); console.log( process("something") ); console.log( process(2) );
The process
function gets called 4 times here. What if while debugging, only the case in which the object is of the type String
is needing to be debugged?
The first way to do this is with just code. The debugger;
is a statement in JavaScript that will trigger a breakpoint in the code. By putting debugger
into the code, the execution will pause at that line. The debugger
can also be wrapped with a conditional statement that only runs when the condition is true.
var process = function( obj ) { var type = Object.prototype.toString.call( obj ); if ( ~type.indexOf( "Str" ) ) { debugger; } return type; };
Now the debugger will only be hit when the type is of “String”.
The other way to set a conditional breakpoint is with the browser’s development tools.
In Chrome…
And in IE10, and I’m pretty sure 9 also.
UPDATE 2/25/2013 several readers asked me to point out that Firefox also supports this feature…
That can definitely be a time saver!