javascriptinternet-explorerinternet-explorer-8consoleundefined

Internet Explorer: "console is not defined" Error


I was using console.log() in some JavaScript I wrote and an error of: console is not defined was thrown in Internet Explorer (worked fine in other browsers).

I have replaced it with:

if (console) console.log("...");

If console is undefined, I would expect the condition to evaluate as false. Ergo, the statement console.log wouldn't be executed and shouldn't throw an error.

Instead, an error of: console is not defined at character 4 is thrown.

Is this a IE bug? Or is that "if" condition really illegal? It seems absurd because if if (console) is illegal, then if (console==undefined) should be illegal too.

How are you supposed to check for undefined variables?


Solution

  • If console itself doesn't exist at all, it throws an error because you're accessing an undefined variable. Just like if(abc) {} throws an error.

    Since console resides in window, and window does always exist, this should work:

    if(window.console) ...
    

    Basically, accessing an property that doesn't exist is free and doesn't throw an error (it just evaluates to undefined, failing the if condition). However, it is illegal to access an undeclared variable.