views:

50

answers:

3

Whats the best approach for preventing errors when console.log calls have been left in JavaScript and it is executed on Browsers without a console or with console deactivated. Is there a way it can be automatically overridden to become a javascript alert for example?

+2  A: 
if(!window.console) console = {log: function(s) {alert(s);}};

You can of course add more of the functions that console normally has.

sje397
A more complete version is [here](http://stackoverflow.com/questions/3265684/using-console-log-with-firebug-ok-locally-not-when-published-to-my-live-site/3265752#3265752)
sje397
Note that the expression `if(!console)` will produce a `ReferenceError` if the `console` identifier hasn't been declared. That's why using the `typeof` operator, or checking `if (!window.console)` is recommended.
CMS
@CMS - fixed, ta
sje397
A: 

Here's what I use :-

if(typeof(console) != "undefined")
Andy Robinson
doesnt work if you've got console calls all through your code tho
seengee
There's no need for parentheses around the `console`: `typeof` is an operator, not a function.
Tim Down
@snaken - True, you'd have to add the check to each, not as simple as @sje397's solution.
Andy Robinson
@Tim - no need, just a preference.
Andy Robinson
+3  A: 

You have to check if the console identifier is available, you can do it either by using the typeof operator, or by checking window.console, because if you access directly an identifier and it's not defined, you will get a ReferenceError.

For example:

if (typeof console == "undefined") {
  window.console = {
    log: function () {
      // do nothing
    }
  };
  console.warn = console.debug = console.log;
} 
CMS