To "check if undefined", the best solution is usually a third one :
Demo
function isDef(obj) {
var undefined;
return obj === undefined;
}
This checks if the object is undefined without losing time with typeof
and this test doesn't validate as true with ""
, null
, NaN
or 0
as would your second test.
The only pitfall is that someone can override the global undefined
object. Not possible in ES5 strict mode, but your code should shield from this. Shadowing undefined
with a local var undefined;
definition does that for you.
Also, by using an isDef
function you allow for better, portable minification and simpler logic.
if (isDef(x)) {
// do something
} else {
// do something else
};