Some progressively better ways to strictly check for undefined in JavaScript.
1. Falsiness
!thing.prop;
Bad Checking if a property is falsy, will be true for undefined
. But it will be true for any falsy JavaScript value, including things like 0
and ''
.
2. Strict equality
thing.prop === undefined;
Meh Checking if a property is strictly equal to undefined
can be problematic, because in a given scope, undefined can be made to be something else. For example, here is how to bind undefined
to 2
:
(function (undefined) { console.log(undefined === 2); })(2);
3. typeof
typeof thing.prop === 'undefined';
Good Calling typeof
on an undefined
property returns the string 'undefined'
. There is a terser way of checking this though.
4. void 0
thing.prop === void 0;
Sweet (and short) Using void
with anything always returns undefined
. It's also the tersest check.