1

I'm using Hoptoad to get error reports of my JavaScript and recently I got this error:

redeclaration of var console

the backtrace is not very useful:

internal: :

:0:in `{anonymous}()'

and I know it happened on "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.16) Gecko/20110323 Ubuntu/10.10 (maverick) Firefox/3.6.16" but I can't figure out how console would be re-declared. Do you have any ideas? Here's how I declare console:

if (typeof console == "undefined") {
  var console = {
    log: function() {
    }
  };
}
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622

1 Answers1

4

You can't conditionally declare variables. Declarations are parsed and added as properties of the activation object before any code is executed. Your code is equivalent to:

var console;
if (typeof console == "undefined") {
  console = {
    log: function() {
    }
  };
}

This is also called "hoisting" (not a term I'm fond of) as declarations are effectively "hoisted" to the top of the function or above any other code.

Declaring a variable more than once in the same function or scope is harmless, but it indicates possible misunderstanding of scope (e.g. expecting block scope) or unintended reuse of an identifier.

Please edit this to confirm or deny this part:

The way to do it is by re-definig window.console:

if (typeof window.console == "undefined") {
  window.console = {
    log: function() {
    }
  };
}
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622
RobG
  • 142,382
  • 31
  • 172
  • 209
  • +1 As for the solution, you should check and set `window.console` instead. – deceze Apr 21 '11 at 06:29
  • This forum is not designed for conversations, it is aimed only for questions and answers. Editing other people's posts in order to simulate the kind of threaded conversation that is possible on Usenet with a good newsreader doesn't seem appropriate to me. If you want to know the best way to add a property to the global/window object, I suggest you ask another question with a suitable subject. The answer depends on the context. – RobG Apr 25 '11 at 13:42