3

When I edit production code (little fixes) I want to add console.log for example, but not to break page for users who don't have firebug or don't use chrome I decide to redefine console object:

if (console == undefined) {
    console = {
        log     : function(){},
        info    : function(){},
        warn    : function(){},
        error   : function(){}
    };
};

After I inserted this code, JS-execution was broken in browsers that don't have console object (IE, firefox without firebug, etc). (By "broken" I mean that code after these lines doesn't execute at all) Why did it happen?

Larry Foobar
  • 11,092
  • 15
  • 56
  • 89

6 Answers6

10

(console == undefined)

will throw a ReferenceError if console is undefined.

Use typeof instead which does not throw ReferenceErrors for undeclared variables

(typeof console === "undefined")

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • I created a console stub for these situations. Check it out at https://github.com/robertofrega/console-stub – Beto Frega Oct 26 '12 at 16:46
5

Try this:

if ( window.console === undefined ) {

    window.console = {
        // Your methods
    }

}
Seth
  • 6,240
  • 3
  • 28
  • 44
  • Yeap, it works! But I posted in plain javascript (without function encapsulation) - so I was already in global scope (in browser it's window). Why doesn't `console` work, but exactly `window.console` ? – Larry Foobar Jul 20 '11 at 15:07
  • @Innuendo: as Raynos's post says, it will throw a ReferenceError if `console` hasn't been declared. If you use `window.console`, then it just returns `undefined`, like accessing a non-existent property of any object. – Reid Jul 20 '11 at 15:09
2

It's not really good to compare a variable to undefined, since undefined is a simple undefined variable.

You can use something like this:

if (!window.console)
  console = {
    log   : function(){},
    info  : function(){},
    warn  : function(){},
    error : function(){}
  };

Edit: I just found this: How do I print debug messages in the Google Chrome JavaScript Console?

Community
  • 1
  • 1
Floern
  • 33,559
  • 24
  • 104
  • 119
1

Any of the answer above should work fine.

One note: You might also add "dir" to your list of empty methods, since people sometimes use console.dir() to print out objects.

Ryan
  • 308
  • 2
  • 8
1

If console is not defined in the js then it will throw an error instead use typeof to check the variable's existense

if (typeof console == 'undefined') { }
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
1

If you change your if(console == undefined) to if(window.console == undefined) everything will work

Akkuma
  • 2,215
  • 3
  • 16
  • 21