Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'console' is undefined error for Internet Explorer

I'm using Firebug and have some statements like:

console.log("..."); 

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() {}}; </script> 

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

like image 228
user246114 Avatar asked Jul 24 '10 19:07

user246114


People also ask

Why does console say undefined?

This is because console. log() does not return a value (i.e. returns undefined). The result of whatever you entered to the console is first printed to the console, then a bit later the message from console. log reaches the console and is printed as well.

What is console in JS?

In JavaScript, the console is an object which provides access to the browser debugging console. We can open a console in web browser by using: Ctrl + Shift + I for windows and Command + Option + K for Mac. The console object provides us with several different methods, like : log() error()


1 Answers

Try

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.

like image 156
kennytm Avatar answered Sep 22 '22 22:09

kennytm