A Javascript debugging tip for Firebug (or “Stop using alert()!”)

Did you know that if you’ve got Firebug for Firefox installed, you can use it for debugging your own code? By calling

console.log("Here's a message!");

Firebug will print the message to it’s internal message log. Neat!

Firebug message console

Now, that’s all good. But let’s say you’re on a project that’s not using a Javascript preprocessor to minify and strip debugging code — which would be the best option. You want the benefits of debugging, but not having to constantly remove debugging code for deployment. If a user doesn’t have Firebug installed, they won’t have a console object. So obviously leaving your debug code in is going to cause an error.

Or will it?

Try adding this code before any of your other Javascript. It will set up a fake console so that if Firebug is not installed, there won’t be any errors.

if(!console || !console.log) {
var console = new Array();
console.log = function () {}
}

Bonus idea! If you combine the idea shown here, with my previous post about debugging Firefox extensions, you can see how to prevent extension debugging from getting in the way of your users.

if(!Firebug || !Firebug.Console || !Firebug.Console.log) {
var Firebug = new Array();
Firebug.Console = new Array();
Firebug.Console.log = function () {}
}

6 thoughts on “A Javascript debugging tip for Firebug (or “Stop using alert()!”)”

  1. Could be a problem if I use a var named console in javascript, if I try to use it like a regular variable?

    Firebug reported this case with the following error: “setting a property that has only a getter”. I changed the name of the var from console to consola, and everything worked right again.

  2. Pingback: Okna Poznan
  3. Pingback: Au Pair Agency

Leave a Reply