(Fix) Javascript: Avoiding “console is undefined”

Testing if a function or object is defined can sometimes cause as many errors as not doing so. What to do?

When developing JavaScript using either Firebug in Firefox or Chrome’s built-in console you will probably at some point be using console.log either for debugging messages or for exception information.

However, when you come to run this code in Internet Explorer, it throws an exception “console is undefined”:

[code lang=”javascript”]
try {
… // code throwing error
} catch (e) {
console.log(e); // throws script error "console is undefined"
}
[/code]

“A-ha” you think; “easily solved will just test if its defined before use”. However things are not so straight forward:

[code lang=”javascript”]
try {
… // code throwing error
} catch (e) {
if (console && console.log) // throws script error "console is undefined"
console.log(e);
}
[/code]

Even though now you are testing to see if it exists before use, you still get:

Console is undefined

While this would normally work for attributes of objects, globally scoped variables work differently. Luckily, all variables in global scope will be declared as attributes on the global window variable. This enables you to test for existence on the window.

Here we’ve wrapped the test up in a LogException function to ease changing of logging methodologies:

[code lang=”javascript”]
function LogException(e) {
if (window.console // check for window.console not console
&& window.console.log) window.console.log(e);
// Other logging here
}

try {
… // code throwing error
} catch (e) {
LogException(e); // works fine
}
[/code]

Note: Its isn’t exclusive to Internet Explorer, it just most visible there; so checking existence of globally scoped functions and variables against window rather than just by name is good practice!