If you are interested in finding out whether a variable has been declared regardless of its value, then using the in
operator is the safest way to go. Consider this example.
// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"
But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in
operator for a more robust check.
"theFu" in window; // true
"theFoo" in window; // false
If you are interested in knowing whether the variable hasn't been declared or has the value undefined
, then use the typeof
operator.
if(typeof myVar != 'undefined')
The typeof
operator is guaranteed to return a string. Direct comparisons against undefined
are troublesome as undefined
can be overwritten.
window.undefined = "omg";
"omg" == undefined // true
if(window.myVar)
will also include all these falsy values, so it's not good:
false
0
""
NaN
null
undefined
Your third case - if (myVariable)
should never throw an error.
Edit: The third case can only throw an error if it hasn't been declared at all, or you're using Object.defineProperty
from ECMAScript 5th ed. where a property can have a backing function, and that backing function throws an error. For example.
// abc was never declared.
if(abc) {}
// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", {
get: function() { throw new Error("W00t?"); },
set: undefined
});
if(myVariable) {}
The if
line will throw an error now. Try it in Chrome.