I noticed an unexplainable behavior of the coffeescript compiler for me :)
For example:
getImage: (req, res) =>
realty_id = req.query.id
if (realty_id?)
Result
ImageController.prototype.getImage = function(req, res) {
var realty_id,
_this = this;
realty_id = req.query.id;
if ((realty_id != null)
But actually the last line should be: if ((typeof realty_id !== "undefined" && realty_id !== null))
When I comment out "realty_id = req.query.id" it works well. Has anyone a explanation for that?
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.