Archive | January 2013

Wrapper for JavaScript console.log

One of the best ways to debug web applications is to use the console.log() function. The catch is while it works in Chrome as well as Firefox (with the Firebug plugin) it causes errors in IE.

Here’s my version of a very simple wrapper function which:
– Prevents errors in IE
– Supports the console functions I regularly use (log, info, warn and error)
– Allows using %s to substitute parameters. ie, log(“length is %s”, foo.length)

window.M5 = window.M5 || {};

$.each(["log","info","warn","error"], function() {
	var name = this;
	M5[name] = function () {
		if(!window.console) return; // prevents errors on IE
		console[name].apply(console, arguments);
	};        
});

// sample usage
M5.log("My test log message");

Note: this requires jQuery and uses the M5 namespace (which you may wish to change for your own application).

%d bloggers like this: