Coffeescript uses the existential operator to determine when a variable exists, and in the coffeescript documentation it shows that something? would compile to something !== undefined && something !== null however I noticed that my version of coffeescript was only compiling this to something !== null so I wrote a test to see how this would effect my code
taco = undefined
if taco?
console.log "fiesta!"
else
console.log "No taco!"
which compiled to
// Generated by CoffeeScript 1.4.0
(function() {
var taco;
taco = void 0;
if (taco != null) {
console.log("fiesta!");
} else {
console.log("No taco!");
}
}).call(this);
and outputted the somewhat unexpected No taco! so my question is two fold. Why does coffeescript no longer check for the value being undefined and why is this suficiant?
The documentation says this about
?:so of course this will say "No taco!":
Your
tacois explicitlyundefinedsotaco?is false.CoffeeScript implicitly declares variables so the JavaScript form of
?is context dependent. For example, if you just say only this:you'll see that
taco?becomestypeof taco !== "undefined" && taco !== null. You still see the "is itnull" check (in a tighter form) but there's also the "is there avar taco" check withtypeof; note that thetypeof tacotest also checks fortaco = undefinedso a stricter!==test can be used to see iftacoisnull.You say this:
but that's not what it is doing, it is actually compiling to
something != null; note the use of "sloppy" type converting inequality (!=) versus the strict inequality (!==) that you claim is there. The difference between!=and!==is important here since:So if you know that variable
vhas been declared (i.e. there isvar vsomewhere) thenv != nullis sufficient to check thatvis neithernullnorundefined. However, if you do not know thatvhas been declared, then you need atypeofcheck to avoid a ReferenceError when you try to compare an undeclared variable withnull. Consider this JavaScript:That will throw a ReferenceError in your face since
tacodoes not exist. This:on the other hand is fine since the
typeofcheck guards against trying to access something that hasn't been declared. I don't think you can construct the first one in CoffeeScript without embedding JavaScript using backticks.