What Means ( Value Unequal Value ) In Javascript?
Solution 1:
In JavaScript NaN is the only value that's not equal to itself. So that's a check for NaN.
Solution 2:
This is the test when count is NaN
because only NaN != NaN
.
Solution 3:
Othere answers has already mentioned why that check is required. But there is another way to assign default value if expected value is a falsy value like NaN
.
The if condition would not be required if you have this:
count = +count || 0; // so if count = NaN which is a falsy value then 0 will be assigned.
Solution 4:
I'll try to summarize what's already been said
if (count != count) {
checks if count
is NaN
. According to the specs:
A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form X !== X. The result will be true if and only if X is a NaN.
(It doesn't matter much in this case, but the polyfill uses !=
instead of !==
as required by the standard).
You might want to ask, why not to use isNaN
? Because isNaN
doesn't do what its name implies - it doesn't check if a value is a NaN
, it checks if the value will beNaN
when converted to a Number. For example, "foo"
is clearly not a NaN
, still isNaN("foo")
will be True
. Conversely, isNaN([[1]])
is False
, although [[1]]
is not a valid number.
How about count = +count || 0
? It's a valid shortcut, but MDN polyfills try to follow the standard as close as possible. The spec for String.repeat
says:
Let n be ToInteger(count).
where ToInteger
is
Let number be ToNumber(argument).
...
If number is NaN, return +0.
Note that it doesn't say "call isNaN", it says "if number is NaN", and a way to find out is to compare number
with itself.
Another option is Number.isNaN
, which, unlike the global isNaN
, doesn't coerce its argument. Number.isNaN(x)
will return true if and only if the x is actually a NaN
Number.isNaN("foo") => falseNumber.isNaN([[11]]) => falseNumber.isNaN(0/0) => true
So the cryptic comparison operator if (count !== count)
can be replaced with if (Number.isNaN(count))
.
Post a Comment for "What Means ( Value Unequal Value ) In Javascript?"