Friday, February 29, 2008

JavaScript: Defining console.log for IE

Front-end web development these days centers around one tool: Firebug. So we go merrily building away in Firefox, and then it comes time to debug in IE, and we’re screwed. Short of installing Firebug Lite (which I have future plans of doing, on demand via Mootools.Asset), but short of that, here’s a little code snippet that defines console.log:

if (!$defined(window.console)) { //$defined() == isDefined()
    window.console = {};
    console.log = window.alert;
}

The bit I missed first time around was testing for window.console, not just console. And the bit of syntax that may look funky, window.console = {};, is an object literal definition. We’re defining window.console as an object with nothing in it. You’ll also see it in my favorite new bit of JavaScript syntax: var namespace = window.namespace || {};. (In JavaScript the OR operator treats the left hand side as a boolean, and then returns the value of either the left or right hand side)

No comments: