The short answer . They are behaviorally equivalent, and compiling != null
is an optimization. Anyway x?
means x
is neither null
nor undefined
.
People ask a lot about this in TrackScript magazine. The reason x != null
not used everywhere, since the compiled output of x?
is that x != null
(or any other comparison with x
) raises a runtime error if x
does not exist. Try it on Node REPL:
> x != null ReferenceError: x is not defined
In "does not exist" I mean no var x
, no window.x = ...
, and you are not in a function where x
is the name of the argument. (The CoffeeScript compiler cannot identify the case of window.x
because it makes no assumptions about the environment you are in.) Therefore, if a var x
declaration does not exist in the current scope or an argument named x
compiler should use typeof x !== "undefined"
to prevent the potential failure of your process.
source share