Archive for October, 2009

Avoiding undefined console

Tuesday, October 27th, 2009

When you’re writing JavaScript it’s handy to use console.log() to output debugging information to the Firebug or Safari console. The only problem is that this code will cause an error on browsers that don’t have a console object, like IE, or like Firefox without Firebug. One solution is to remove or comment out all the console.log statements, but this is tedious and easy to forget. There are two better options.

First, if you’re trying to debug your code on other web browsers, you can include Firebug Lite on your page. This script mimics Firebug’s functionality in other browsers. It also handles any console.log statements, so your script won’t crash on these pages.

If you simply want to avoid errors, you can define console.log to be an empty function. Add this line at the top of your main script:

// Define console to avoid errors when Firebug isn't available
if(!window.console){ window.console = {log:function(){}}; }

This checks to see if Firebug is turned on (by looking for a global console object. If console doesn’t exist, it creates console and adds log as a function that doesn’t do anything. If you have used other console features, like .info() or .time(), you would have to add those as empty functions as well.