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
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);
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!
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.