Javascript – ‘console’ is undefined error for Internet Explorer


I'm using Firebug and have some statements like:


in my page. In IE8 (probably earlier versions too) I get script errors saying 'console' is undefined. I tried putting this at the top of my page:

<script type="text/javascript">
    if (!console) console = {log: function() {}};

still I get the errors. Any way to get rid of the errors?

Best Solution


if (!window.console) console = ...

An undefined variable cannot be referred directly. However, all global variables are attributes of the same name of the global context (window in case of browsers), and accessing an undefined attribute is fine.

Or use if (typeof console === 'undefined') console = ... if you want to avoid the magic variable window, see @Tim Down's answer.