I noticed something a little odd with the CoffeeScript compilier and was wondering if this was correct behavior or not. If it is correct I’m curious why there is a difference..
Given the following CoffeeScript:
if @myVar?
alert myVar
I was expecting it to compile to JavaScript like this:
if (typeof this.myVar !== "undefined" && this.myVar !== null) {
alert(myVar);
}
But instead what the CoffeeScript compiler outputs is this:
if (this.myVar != null) {
alert(myVar);
}
If I don’t reference this (or any other parent object), the CoffeeScript compiles as I would expect.
Is this the correct behavior? If so, why does it work different when using this?
Edit:
To add a little more clarification. This doesn’t happen with only this, but any other properties of objects. For instance, if I were replace the above CoffeeScript with what’s below it still would compile with only “!= null”…
if myVar.myProp?
alert myVar
In the case of:
Coffeescript compiler is able to see that
myVaris really defined in the first line, so it can omittypeof myVar !== "undefined"check.But in this case:
compiler can’t guarantee that
myVaris actually defined, so extra check is required:So, the answer is: Coffeescript compiler tries to be smart to produce efficient code.
EDIT
The way Coffeescript deals with properties is also correct:
this.propwill returnundefinedif property is not defined.!=will convert it to null. That is why we don’t need additional check.In few words:
typeofundefined— just!=is enough