If I pass a variable to the existential operator in Coffescript it is converted to a pair of !== comparisons:
compiles to
Coffeescript ------> JS
a? typeof a !== "undefined" && a !== null;
But if I use a literal or expression it instead uses a != comparison:
compiles to
Coffeescript ------> JS
17? 17 != null;
//same thing for regexps, strings, function calls and other expressions
//as far as I know.
Is there any reason for preferring the double !==s over the shorter != null, other then perhaps making JSLint happy?
Short answer: They’re behaviorally equivalent, and the
!= nullcompilation is an optimization. Either way,x?means thatxis neithernullnorundefined.People ask about this a lot on the CoffeeScript issue tracker. The reason
x != nullisn’t used everywhere as the compiled output ofx?is thatx != null(or any other comparison againstx) causes a runtime error ifxdoesn’t exist. Try it on the Node REPL:By “doesn’t exist,” I mean no
var x, nowindow.x = ..., and you’re not in a function wherexis the name of an argument. (The CoffeeScript compiler can’t identify thewindow.xcase because it doesn’t make any assumptions about the environment you’re in.) So unless there’s avar xdeclaration or an argument namedxin the current scope, the compiler has to usetypeof x !== "undefined"to prevent your process from potentially crashing.