23

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?

Rohwedder
  • 1,483
  • 4
  • 18
  • 31
matteo
  • 2,653
  • 6
  • 39
  • 51

9 Answers9

31

Other answers gave you the root cause. However, there's a better solution than using if before any call to console.*

Add this (once) before including any of your scripts that use console:

//Ensures there will be no 'console is undefined' errors
window.console = window.console || (function(){
    var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile = c.clear = c.exception = c.trace = c.assert = function(s){};
    return c;
})();

This will create a 'pseudo' console only if it doesn't exist, so that 'console is undefined' errors will go away and you won't have to ask if console exists everytime. With this, you just call console.log or any console method anywhere, without problems.

Hope this helps. Cheers

Edgar Villegas Alvarado
  • 17,527
  • 1
  • 39
  • 59
  • 1
    I made an edit above - use a parameter (I chose the name `logMsg` arbitrarily) in the function signature to be consistent since you will be passing something to be printed to the log. This also avoids any intellisense errors in a JS enabled IDE – Flak DiNenno Feb 04 '13 at 23:17
  • I still face the error but managed it by removing initial window (console = window.console || (function(){... & it works for me on IE 8 onwards. – SarangK Feb 09 '16 at 09:59
24

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.

pimvdb
  • 141,012
  • 68
  • 291
  • 345
7

in internet explorer the console object is not actually defined unless your developer tools are open at the time the window loads.

to fix your problem, wrap all your console prints in an if statement:

if (typeof window.console !== 'undefined') {
    ...
}

you also need to refresh each page after you open the developer tools in order to see the console prints. <3 IE

jbabey
  • 42,963
  • 11
  • 66
  • 94
4

This is a funny thing about undeclared variables. The JS engine tries to resolve the variable to a property of window. So usually, foo == window.foo.

But, if that property does not exist, it throws an error.

alert(foo); // Syntax error: foo is not defined

(Should be "foo is not declared" imho, but whatever.) That error does not occur when you explicitly reference the window's property:

alert(window.foo); // undefined

...or declare that variable:

var foo;
alert(foo); // undefined

...or use it for initialization:

foo = 1; // window.foo = 1

The strange thing is that the typeof operator also prevents this error:

alert(typeof foo); // "undefined"

So, to sum things up: You cannot use undeclared variables in expressions unless there's a property of window with the same name, or you use it as an operand of typeof. In your example, window.console does not exist, and there's no var declaration. That's why you get an error.

user123444555621
  • 130,762
  • 25
  • 104
  • 122
3

How about this? Haven't tried it though

if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} };
Chetter Hummin
  • 6,249
  • 8
  • 30
  • 44
1

Edit of @yckart's answer

Using c.length as input to a function which defines c won't work. Also you're just reassigning items in the array with noop when you should be adding methods to window.console.

(function(w){
  var c = 'assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn'.split(','),
  noop = function () {};

  w.console = w.console || (function (len) {
    var ret = {};
    while (len--) { ret[c[len]] = noop; }
    return ret;
  }(c.length));
})(window);
Community
  • 1
  • 1
0

You can use the below to give an extra degree of insurance that you've got all bases covered. Using typeof first will avoid any undefined errors. Using === will also ensure that the name of the type is actually the string "undefined". Finally, you'll want to add a parameter to the function signature (I chose logMsg arbitrarily) to ensure consistency, since you do pass whatever you want printed to the console to the log function. This also keep you intellisense accurate and avoids any warnings/errors in your JS aware IDE.

if(!window.console || typeof console === "undefined") {
  var console = { log: function (logMsg) { } };
}
Flak DiNenno
  • 1,941
  • 2
  • 25
  • 52
0

Inspired by @Edgar Villegas Alvarado answer, completed the methods and made it a bit simpler:

(function(w){
  var c = 'assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn'.split(','),
  noop = function () {};

  w.console = w.console || (function (len) {
    var ret = {};
    while (len--) { ret[c[len]] = noop; }
    return ret;
  }(c.length));
})(window);

Edited to put into an IIFE and fix a syntax error!

Community
  • 1
  • 1
yckart
  • 28,174
  • 7
  • 112
  • 121
0

Some browsers do not have console enabled when the dev-tools is closed. Also, one would encounter this issue with WebViews or iFrames where console is disabled.

The error in these cases is - Uncaught ReferenceError: console is not defined

Inspired by many answers on here, I developed a library for this usecase: https://github.com/sunnykgupta/jsLogger

Features:

  1. It safely overrides the console.log.
  2. Takes care if the console is not available (oh yes, you need to factor that too.)
  3. Stores all logs (even if they are suppressed) for later retrieval.
  4. Handles major console functions like log, warn, error, info.
Sunny R Gupta
  • 4,687
  • 1
  • 30
  • 40