If we 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.
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.
If we 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.
As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.
if (window.myVar) will also include these falsy values, so it's not very robust:
Thanks to @CMS for pointing out that our third case -
if (myVariable) can also throw an error in two cases. The first is when the variable hasn't been defined which throws a ReferenceError.
The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,
Using typeof is my preference. It will work when the variable has never been declared, unlike any comparison with the == or === operators or type coercion using if. (undefined, unlike null, may also be redefined in ECMAScript 3 environments, making it unreliable for comparison, although nearly all common environments now are compliant with ECMAScript 5 or above).
We need to use typeof .
If it is undefined, it will not be equal to a string that contains the characters "undefined", as the string is not undefined. We can check the type of the variable:
Sometimes we don't even have to check the type. If the value of the variable can't evaluate to false when it's set (for example if it's a function), then we can just evalue the variable. Example:
Note that strict comparison (!==) is not necessary in this case, since typeof will always return a string.