Setting Firebug Ablaze With 'debug;'

December 2nd 2010

Firebug is a tool well loved by all web developers. You can modify CSS on the fly. You can view your DOM. You can easily view JavaScript errors. You can even debug JavaScript. I’ve never really used it for that though. I’d always found setting breakpoints in Firebug to be tedious. But after today, things have changed for me.

Setting Breakpoints Within Firebug

Whenever I wanted to set a breakpoint, I would first have to click through a file list in the script tab, then scroll through the source to the line I wished to set the breakpoint on, click on it, then reload the page. Too many steps. I’ve always opted to litter my code with console.log(); instead. That much simpler to do than setting a breakpoint. This console technique has served me well for the past several years.

Setting Breakpoints Within JavaScript

While working on a project with my fellow developers at Mutually Human Software, I found myself having to set several brakpoints for some JavasScript. Tired of this, I did a Google search for “setting a firebug breakpoint in code”. The Google gods smiled upon me and blessed me this this little gem: how to set breakpoints from within JS code?.

Amazing! You can set breakpoints from within your JavaScript. Simply call debugger; in the place where you would like the browser to stop executing the JavaScript and hand control over to you.

Here is a small example. Say you have an HTLM file that loads the following JavaScript file hello_debugger.js:

If you start Firebug and view the HTML file, the “debugger;” keyword gets interpreted and Firebug breaks the execution of the code.

You can set a watch expression or peek at the status of DOM elements at this point. In addition, the console has the same context as the location of the breakpoint.

In this snapshot, you can see that the console has full knowledge of anObject and anArray. This is the same context as the closure that lexically scopes the contents of the hello_debugger.js file. From the Firebug console, if you type in:

Then you’ll see from the alert that the object is in-fact the one you defined in your file.

I like this method of using console rather than setting up watches. Since I’m a rubyist, using the console feels more like using the Ruby debugger as opposed to using the GUI based tools provided by Firebug.

Calling debugger; from code also works in Google Chrome. I haven’t tried this with any other browsers though. So give it a try. Hopefully you find this to be a useful item to have in your toolbox too.

blog comments powered by Disqus