How to Prevent Javascript Error When Using console.log in Internet Explorer

Whenever I code some Javascript, for debugging purpose I’m using console.log statement. It runs well on my Chrome and Firefox (with Firebug add-on installed). But when it comes to Internet Explorer, my script will throws some exceptions.

The new version of Internet Explorer is bundled with Developer Tools (by pressing F12 button). When the user has activated the Developer Tools, by pressing F12 button, and then refresh the page, the script runs well.

But it’s nearly impossible to tell the user to activate the Developer Tools whenever they want to access the page. Therefore we need to define our own console.log in our script. Put this line on the very top of your Javascript code.

if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} };

That’s it. Now we have define our own console.log!