Reputation: 16299
I'm a bit confused about how best to check if a variable is undefined or not in javascript. I've been doing it like this:
myVar === undefined;
But is it better in all cases to use typeof instead?
typeof myVar === undefined;
And what about the use of undefined
vs "undefined"
, which I've also seen?
Upvotes: 14
Views: 2672
Reputation: 2000
I believe that in the most common cases, e.g. when checking if a parameter is passed through a function, myVar === undefined
is enough, as myVar will be always declared as a parameter
Upvotes: 0
Reputation: 437336
This is the best way to check -- totally foolproof:
typeof myVar === "undefined"
This is OK, but it could fail if someone unhelpfully overwrote the global undefined
value:
myVar === undefined;
It has to be said that ECMAScript 5 specifies that undefined
is read-only, so the above will always be safe in any browser that conforms.
This will never work because it ends up comparing "undefined" === undefined
(different types):
typeof myVar === undefined;
Upvotes: 22
Reputation: 173552
This test would always work as expected:
typeof a === 'undefined'
Since the value of undefined
can be changed, tests like these aren't always reliable:
a = {}
a.b === undefined
In those cases you could test against void 0
instead:
a.b === void 0
// true
However, this won't work for single variable tests:
a === void 0 // <-- error: cannot find 'a'
You could work around that by testing against window.a
, but the first method should be preferred.
Upvotes: 2