3

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?

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.