Debugging JavaScript using Firebug – An alternative to alert();

So as you may already know, Firebug must be one of the most important tools a developer can have in their utility belt.

The more I use Firebug, the more I realise that I'm not using it to its full potential. One of the most useful aspects of Firebug is its ability to help me debug code fast.

It's amazing how many developers out there have Firebug installed, but when debugging JavaScript always resort to using the alert(); function.

Well if your one those developers, then you need to stop littering your code with //alert(foo); and start using console.log()!

As you can see, console.log() does exactly what it says on the tin, it logs content to the console.

So if we ran the following in our page:

Then opened up Firebug (Firefox) to view the Console, you would be able to see "Now this is debugging in style!".

Now that may seem a bit pointless at first (hopefully not), but swap the showy string for a variable like so:

And the whole worlds your oyster right?

Some other cool and equally handy items to remember are that your not bogged down to just using the console.log().

There's a whole range of expressions you can use to increase the significance of your log. Lets take the above example and implement these:

Here we have the following:

console.log();

A log in its most basic form, neither an error or a warning. The
basic log is the only one that doesn't supply a hyperlink to the line that your debugging.

console.debug();

Using debug is the same as using log, except your log will also include a hyperlink to the line of code you are debugging.

console.info();

Using info will put a blue information icon next to your log with in the console.

console.warn();

Using warn will add a yellow warning icon next to your log with in the console.

console.error();

Using error will add a red error icon next to your log with in the console.

Pushing the log even further!

String Arguments

Things to remember when using string arguments with in the log are:

%s - String

%d, %i - Integer (numeric formatting is not yet supported)

%f - Floating point number (numeric formatting is not yet supported)

%o - Object hyperlink

Troubleshooting console is not defined

You may need to check that the console is enabled:

Troubleshooting

If it is enabled and your still getting the error then try adding:

To the top of your JavaScript.

Troubleshooting

And if that still doesn't work then you may need to relaunch
Firefox. I know that sounds like the old I.T. "Have you tried rebooting?" get out clause, but sometimes it sorts my Firefox issues out as a last resort.

Reference Article - Firebug API Wiki : http://bit.ly/aWZ2h2

Related Links

I hope that you found something in this post useful.

Hopefully next time your debugging that next piece of JavaScript you'll remember to use the console.

Leave a comment -