Problem
In JavaScript, what is the best approach to see if a variable is undefined?
I’ve seen a few possibilities:
if (window.myVariable)
Or
if (typeof(myVariable) != "undefined")
Or
if (myVariable) // This throws an error if undefined. Should this be in Try/Catch?
Asked by makerofthings7
Solution #1
The in operator is the safest way to determine whether a variable has been declared regardless of its value. Consider the following scenario:
// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"
However, in some circumstances, because the variable or property was declared but not initialized, this may not be the desired outcome. For a more reliable check, use the in operator.
"theFu" in window; // true
"theFoo" in window; // false
If you want to find out if a variable hasn’t been declared or if its value is undefined, use the typeof operator, which will always return a string:
if (typeof myVar !== 'undefined')
Comparisons to undefined are problematic because undefined might be overridden.
window.undefined = "foo";
"foo" == undefined // true
As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.
(window.myVar) will also include these erroneous values, making it insecure:
false
0
""
NaN
null
undefined
@CMS pointed out that your third example – if (myVariable) – can potentially result in an error in two situations. The first is when the variable isn’t defined and a ReferenceError is thrown.
// abc was never declared.
if (abc) {
// ReferenceError: abc is not defined
}
The other scenario is when the variable is defined but contains a getter method that throws an exception when called. As an example,
// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", {
get: function() { throw new Error("W00t?"); },
set: undefined
});
if (myVariable) {
// Error: W00t?
}
Answered by Anurag
Solution #2
I personally use
myVar === undefined
Please note that === is used instead of == and that myVar has already been declared (not defined).
typeof myVar === “undefined” does not sit well with me. It’s overly long and unneeded, in my opinion. (I can accomplish the same thing with less code.)
When they read this, some people will collapse over in anguish and scream: “Wait a minute! WAAITTT!!! Undefined is a term that can be redefined!”
Cool. This is something I’m aware of. Most variables in Javascript, on the other hand, can be redefined. Should any built-in identifier that can be redefined be avoided at all costs?
Good for you if you follow this rule: you aren’t a hypocrite.
The problem is that developers must rely on redefinable identifiers to be what they are in order to conduct a lot of real work in JS. I haven’t heard anyone advise me that I shouldn’t use setTimeout because it can be abused.
window.setTimeout = function () {
alert("Got you now!");
};
In the end, the “it can be redefined” argument for not using a raw === undefined is a load of nonsense.
(Why are you naively adding untested library code into your code base if you’re still afraid of undefined being redefined? Or, to put it another way, a linting tool.)
This technique, like the typeof approach, can also “find” undeclared variables:
if (window.someVar === undefined) {
doSomething();
}
Both of these strategies, however, have a flaw in their abstraction. I strongly advise you not to use it, or even to use it at all.
if (typeof myVar !== "undefined") {
doSomething();
}
Consider:
var iAmUndefined;
You may need to use the in operator to determine whether a variable is declared or not. (In many circumstances, the code O o will suffice.)
if ("myVar" in window) {
doSomething();
}
But hold on! There’s more to come! What if there’s some prototype chain wizardry going on…? Even the superior in operator is no longer sufficient. (Okay, I’m done with this portion except to note that === undefined (and ****cough**** typeof) works fine 99 percent of the time.) If you’re really interested, you can read about it on your own.)
Answered by Thomas Eding
Solution #3
2020 Update
With the widespread acceptance of ECMAScript 5, one of my justifications for preferring a typeof check (that undefined can be redefined) became obsolete. The other, that typeof can be used to determine the type of an undeclared variable, has always been a niche. As a result, in most cases, I now advocate doing a direct comparison:
myVariable === undefined
2010’s original response
My preferred method is to use typeof. Unlike comparisons with the == or === operators or type coercion with if, it will operate even if the variable has never been declared. (Unlike null, undefined can be redefined in ECMAScript 3 environments, making comparisons inaccurate; however, practically all common environments now support ECMAScript 5 or higher).
if (typeof someUndeclaredVariable == "undefined") {
// Works
}
if (someUndeclaredVariable === undefined) {
// Throws an error
}
Answered by Tim Down
Solution #4
You may use typeof in the following way:
if (typeof something != "undefined") {
// ...
}
Answered by Jacob Relkin
Solution #5
This piece was written about five years ago, and JavaScript has come a long way since then. I noticed no consistent difference between the following test methods after performing the experiments described in the original post:
The differences were insignificant even after I adjusted the tests to prevent Chrome from optimizing them away. As a result, for clarity, I’d now advocate abc === undefined.
Chrome:/version: version: version: version: version: version: version: version: version: version: version
The following was slightly faster than a typeof test in Google Chrome:
if (abc === void 0) {
// Undefined
}
The distinction was insignificant. This code, on the other hand, is more simple and straightforward at a glance for someone who understands what void 0 signifies. It’s worth noting, though, that abc must still be disclosed.
When compared directly to undefined, typeof and void were substantially faster. In the Chrome developer console, I used the following test format:
var abc;
start = +new Date();
for (var i = 0; i < 10000000; i++) {
if (TEST) {
void 1;
}
}
end = +new Date();
end - start;
The following were the outcomes:
Test: | abc === undefined abc === void 0 typeof abc == 'undefined'
------+---------------------------------------------------------------------
x10M | 13678 ms 9854 ms 9888 ms
x1 | 1367.8 ns 985.4 ns 988.8 ns
The first row is measured in milliseconds, whereas the second row is measured in nanoseconds. A 3.4 nanosecond difference is insignificant. In following experiments, the times were rather constant.
Answered by Zenexer
Post is based on https://stackoverflow.com/questions/3390396/how-can-i-check-for-undefined-in-javascript