Avoid Logs To The Console Breaking In IE7 & 8

As I’m sure you’re aware, if you try to log to the console in a browser like IE7 or 8 where there is no console like this:

Then it will break your script. Of course, the simple solution to this is to make sure there’s no call to the console object in your code, however during testing this can be quite tedious. At the expense of a few lines of code you can get around this by adding this at the top of your JS file:

Firstly we create a new object called c, and then add a method called log which first checks if the console exists, and then calls the regular console.log() method if it does.

You would use this the same as the console, except it’s a bit quicker to write:

Now if you accidentally, or purposefully, leave that in your code it won’t break IE7 or 8, or any other browser which doesn’t implement the console object. You could of course add other console methods quite easily.

Because I’m lovely, here’s an already minified version of the  c object, so it takes up even less space.

Go forth and log to the console as much as you wish.

Kane Cheshire

Author: Kane Cheshire

I'm a software developer (and sort of designer) from Hertfordshire. I spend a lot of time learning, travelling and flying my drone. I made MacID. You can check out some of my favourite photographs from travelling at http://kane.codes. I'm also the creator and lover of Twicnic, an annual Twitter picnic event.

3 thoughts on “Avoid Logs To The Console Breaking In IE7 & 8”

  1. Is there some reason why we’re specifying window when that’s default? Burt I like your idea of creating it if it doesn’t exist, that’s nice, but I do believe without typeof in there, IE will still fail it. I’d go with this: if ( typeof console === "undefined" ) console = { log: function(){} };

Leave a Reply

Your email address will not be published. Required fields are marked *