Escaping Console.log()

Firebug icon Ray Camden just Twittered about checking in code that still has console.log() in the Javascript. He rightly points out that console.log() causes problems for browsers that don't understand it, but you don't really have to have Firebug installed as some browsers like Chrome understand it natively. Rather than try to purge my code of console.log(), and need them again later, my solution is to add an "escape" that lets console.log() evaluate harmlessly on browsers that don't support it. Click more to see the code.

The Javascript is really simple:


if( typeof console == 'undefined' ){
    console = {
        log: function () {}
    };
}

And you can fit it on one line:


if( typeof console == 'undefined' ){ console = { log: function () {} }; }

Technically you should check for the existence of console, and then separately check for the log method, but its working out OK this way.

 

Comments

Raymond Camden's Gravatar I still say you should forward them to Firefox's web site. ;)
Jon Hartmann's Gravatar @Ray: Haha, yeah I'd love to do that. I do use http://www.pushuptheweb.com/ on my site though, but I can't get away with that for client projects.
Comments are not allowed for this entry.
Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a Javascript fanatic, UX/UI evangelist and former ColdFusion master. I blog about mysterious error messages, user interface design questions, and all things baffling and irksome about programming for the web.

Learn more about me on LinkedIn.