What does (unequal value value) mean in JavaScript?

I saw these fragments in polyfill shown on this MDN Documentation:

 // Casts the value of the variable to a number.
 // So far I understand it ...
 count = +count;
 // ... and here my understanding ends.
 if (count != count) {
   count = 0;
 }

I had no idea about the goal.

How can there be something unequal?

+4
source share
4 answers

In JavaScript, NaN is the only value that is not equal to itself. So check for NaN.

+5
source

This is a test when count NaN, because only NaN != NaN.

+4
source

Othere , . , - , NaN.

if , :

count = +count || 0; // so if count = NaN which is a falsy value then 0 will be assigned.
+2

if (count != count) {

, count NaN. :

ECMAScript , X NaN X! == X. , X NaN.

( , polyfill != !==, ).

, , isNaN? isNaN , , , NaN, , NaN . , "foo" NaN, isNaN("foo") True. , isNaN([[1]]) False, [[1]] .

count = +count || 0? , MDN . spec String.repeat :

n - ToInteger (count).

ToInteger

ToNumber ().

...

NaN, +0.

Please note that he does not say “call isNaN”, he says “if the number is NaN”, and the way to find out is to compare numberwith yourself.

Another option Number.isNaN, which, unlike the global one isNaN, does not force its argument. Number.isNaN(x)will return true if and only if x is actually NaN

Number.isNaN("foo")  => false
Number.isNaN([[11]]) => false
Number.isNaN(0/0)    => true

Thus, the cryptic comparison operator if (count !== count)can be replaced by if (Number.isNaN(count)).

0
source

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


All Articles