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?
TLDR; Don't use the undefined primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference.
When using x === undefined , JavaScript checks if x is a declared variable that is strictly equal to undefined . If you want to check if x is strictly equal to undefined regardless of whether is has been declared or not, you should use typeof x === 'undefined' .
myVariable is declared and not yet assigned with a value. Accessing the variable evaluates to undefined . An efficient approach to solve the troubles of uninitialized variables is whenever possible assign an initial value. The less the variable exists in an uninitialized state, the better.
Here the assigned variables don't have any value but the variable exists. Here the type of variable is undefined. If you assigned a value(var geeks === undefined ) it will show, if not it will also show undefined but in different meaning. Here the undefined is the typeof undefined.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With