Is there a difference between checking for inequality (! ==) on undefined and zero and just checking for inequality corcive (! =) Against null?

If I pass the 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, instead it 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 double !== shorter != null , other, is it possible that JSLint will be happy?

+4
source share
2 answers

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.

+4
source

I understand why people find this confusing. In ECMAScript:

 a? 

is equivalent to:

 typeof a !== 'undefined' && a !== undefined && a !== null && a !== 0 && a !== false && a !== ''; 

Coffeescript refactoring for:

 typeof a !== "undefined" && a !== null; 

means that:

 var a = false; a?; // evaluates to true? 

Is it correct?

+1
source

Source: https://habr.com/ru/post/1384030/


All Articles