How to Dynamically and Programmatically add Breakpoints in JavaScript
Debugger
Little known yet immensely useful fact is that you can use the keyword debugger;
to stop JavaScript execution and bring up your browser’s debugger/web inspector (Firebug, WebKit Developer Tools, etc).
Programmatically
You can take this a step further by creating a global
window.DEBUG = true; // toggles programmatic debugging
flag with a global check debug function, like so:
window.CHECK_DEBUG = function() {
if (window.DEBUG) { debugger; }
}
And then insert the following in any function you’re concerned about debugging:
function foo() {
CHECK_DEBUG();// foo's usual procedure ...
}
Dynamically
To take this a step further (and to take a page out of Firebug's debug()
and undebug()
wrapper functions) you can decorate the native JavaScript Function object like so:
Function.prototype.debug = function(){
var fn = this;
return function(){
if (window.DEBUG) { debugger; }
return fn.apply(this, arguments);
};
};
Then you can dynamically debug any function by calling:
foo = foo.debug();
Happy debugging!