Is it unsafe to compare a variable against undefined?
if(foo == undefined)
vs
if(foo == 'undefined')
Is the first example sufficient? Or should it be something like
if('undefined' in window){
//compare against undefined
} else {
//compare against 'undefined'
}
since undefined exists on the window object? Will it exist in all browsers? Or should I simply compare to == 'undefined'? I’ve found some similar questions on SO, but no answers regarding the existance of the undefined property on the window object.
I think you’re getting mixed up between
foo == undefinedandtypeof foo == "undefined".Both will yield the same result unless the variable
undefinedhas been set to something else in the current scope. In this case,foo == undefinedwill compare against that, where-astypeof foo == "undefined"will still resolve correctly.Whether it’s a real world scenario that
undefinedwill ever be set to something else is debatable, and I’d question the validity of the library/ code that does that… Because of this however, it’s deemed good practise to always usetypeof foo === "undefined".I’d also be wary about using
foo == undefinedagainstfoo === undefined(note the triple equals, which does not use type-coercian, compared to==which does).Using
==, you run the risk of things likenull == undefined; // true, where-asnull === undefined; // false. This is a good example of why you should always use===.tl;dr:
typeof foo === "undefined";