Debugging JavaScript the easy way

By David Pratt / Tags: , / 1 Comment / Published: 21-11-09

If you use the firebug function console.log() liberally throughout your javascript when you’re developing, you’ll know it’s a bit of a pain when you want to test your code in a browser that hasn’t got a version of firebug enabled (as the non-existence of the console object will prevent the javascript from working properly).

I wrote this simple bit of code to get around that problem:

if(!window.console){
	var console = {
		log : function(msg){
			alert(msg);  //You could leave this statement out if you wanted the debugging to be silent when firebug isn't enabled
		}
	}
}

All it does is test for the existence of the console object, and if it doesn’t exist use the classic debuggers friend, alert(). You could extend this to incorporate console.debug() etc. but if you’re going to go to them lengths, then you may as well just use firebug lite.

Another way I’ve seen described in the past for manging this problem is to use a log() function that might look something like:

function log(msg) {
	if(console){
		console.log(msg);
	}else{
		alert(msg);
	}
}
log("debug message");

Another way would be to do it the other way around and overwrite the alert function with console.log if it exists:

if ( window.console ){
	if ( window.console.log ) {
		window.alert = console.log;
	}
}

All three methods mentioned above are a lot more effective than commenting out every instance of console.log in your code! Come on, we’ve all done it…

Category: Tech

Tags: ,

Posted: on November 21st, 2009 at 3:08 pm.

Feeds: RSS 2.0

One Response to “Debugging JavaScript the easy way”

Leave a reply