I would like to use the CoffeeScript existential operator to check some object properties for undefined. However, I encountered a little problem.
Code like this:
console.log test if test?
if (typeof test !== "undefined" && test !== null) console.log(test);
console.log test.test if test.test?
if (test.test != null) console.log(test.test);
console.log test.test if typeof test.test != "undefined" and test.test != null
This is a common point of confusion with the existential operator: Sometimes
typeof test !== "undefined" && test !== null
and other times it just compiles to
x != null
The two are equivalent, because
x != null will be
x is either
x != null is a more compact way of expressing
(x !== undefined && x !== null). The reason the
typeof compilation occurs is that the compiler thinks
x may not have been defined at all, in which case doing an equality test would trigger
ReferenceError: x is not defined.
In your particular case,
test.test may have the value
undefined, but you can't get a
ReferenceError by referring to an undefined property on an existing object, so the compiler opts for the shorter output.