TLDR: In general, when checking for presence of a variable, foo?
will be the safest.
foo?
checks that foo is neither null nor undefined. It will not throw an error if the foo has not been declared:
typeof foo !== "undefined" && foo !== null;
> false
var foo = null;
typeof foo !== "undefined" && foo !== null;
> false
var foo = 123;
typeof foo !== "undefined" && foo !== null;
> true
foo isnt undefined
checks that foo is not equal to undefined. If foo has not been declared it will throw an error. If foo is null it will return true:
foo !== void 0;
> ReferenceError // OH NO!
var foo;
foo !== void 0;
> false
var foo = 123;
foo !== void 0;
> true
var foo = null;
foo !== void 0;
> true // OH NO!
NOTE: void 0
is equivalent to undefined