tldr; typeof x !== "undefined"
is not needed with local JavaScript variables.
The SO question CoffeeScript Existential Operator and this has information on why CoffeeScript will make this optimization.
Now, to see why it is a valid code generation in the presented case:
-> x x != null typeof x !== "undefined" && x !== null
---------- --------- -------------------------------------
ANY_TRUE true true
0 true true
null false false
undefined false false
So, according to the logic tables, they are semantically equivalent. It is the "non strict" nature of the ==
operator that determines the - perhaps surprising - result of this comparison: SO questions on the topic abound.
However, here is the important difference of when/why typeof x !== "undefined"
is sometimes used: it will not result in a ReferenceError
. If x
is known to be a local variable then there is no such consideration and the shorter (!=
) JavaScript expression can be safely used.
In the case when the assignment in CoffeeScript is commented out, there is no local variable/binding with the name reality_id
- note that the var
statement is also different - and CoffeeScript inserts the additional guard as appropriate.