What is the most appropriate way to test if a variable is undefined in JavaScript?
I’ve seen several possible ways:
if (window.myVariable)
Or
if (typeof(myVariable) != "undefined")
Or
if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
If you are interested in finding out whether a variable has been declared regardless of its value, then using the
inoperator 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
inoperator for a more robust check.If you are interested in knowing whether the variable hasn’t been declared or has the value
undefined, then use thetypeofoperator, which is guaranteed to return a string:Direct comparisons against
undefinedare troublesome asundefinedcan be overwritten.As @CMS pointed out, this has been patched in ECMAScript 5th ed., and
undefinedis non-writable.if (window.myVar)will also include these falsy values, so it’s not very robust:Thanks to @CMS for pointing out that your third case –
if (myVariable)can also throw an error in two cases. The first is when the variable hasn’t been defined which throws aReferenceError.The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,