0

I was looking through idiomatic.js and notice the following lines in the type checking secton:

undefined:

Global Variables:

typeof variable === "undefined"

Local Variables:

variable === undefined

This section appears to originally be based on the jQuery style guide

I'd been taught that the first form was safer since undefined can be redefined to another value. I also don't know of any reason that the 1st form doesn't work for local variables.

It seems to work fine in this fiddle. Can anyone explain why this style makes sense?

var undefined = 2;

function test(){
  var x;
    
    alert("1: " + (typeof x == "undefined"));
    alert("2: " + ( x  === undefined)); 
    
}

test();  //alerts "1: true", then  "2: false"
Community
  • 1
  • 1
Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
  • 1
    The real reason behind #1 is to avoid a `ReferenceError`. There's no need to avoid that when testing local variables. – John Dvorak Mar 30 '13 at 19:17
  • @Bergi thanks that second link was very helpful. Makes sense if jQuery defines their own version of undefined. Less sense that Idiomatic.js copied that as a general recommendation though. – Ben McCormick Mar 30 '13 at 22:58
  • 1
    I hate automatical deletion of edited dupe-comments. For future reference, the "second link" (and better duplicate) was [variable === undefined vs. typeof variable === “undefined”](http://stackoverflow.com/questions/4725603/variable-undefined-vs-typeof-variable-undefined?lq=1) – Bergi Mar 31 '13 at 13:09

0 Answers0