Why does (1 < NaN)
give back false
and not undefined
(in JavaScript)?
In "11.8.5 The Abstract Relational Comparison Algorithm" it says that if either of the values is NaN (after ToPrimitive and ToNumber which should not affect NaN in my view) the result is undefined
.
In FF and Chrome I get:
console.log(1 < NaN);
// false
Why is that?
There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.
Although either side of NaN===NaN contains the same value and their type is Number but they are not same. According to ECMA-262, either side of == or === contains NaN then it will result false value.
This means that in JavaScript, isNaN(x) == true is equivalent to x - 0 returning NaN (though in JavaScript x - 0 == NaN always returns false, so you can't test for it). Actually, isNaN(x) , isNaN(x - 0) , isNaN(Number(x)) , Number.
isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.
Because the <
operator returns false
when the abstract relational algorithm returns undefined
. See Section 11.8.1:
11.8.1 The Less-than Operator (
<
)The production RelationalExpression : RelationalExpression < ShiftExpression is evaluated as follows:
- Let lref be the result of evaluating RelationalExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating ShiftExpression.
- Let rval be GetValue(rref).
- Let r be the result of performing abstract relational comparison lval < rval. (see 11.8.5)
- If r is undefined, return false. Otherwise, return r.
This is true of all of the relational operators. The algorithm has an undefined
outcome, but the operators convert that to false
. And that makes sense. 1
isn't < NaN
(nor is it > NaN
, or == NaN
, or... :-) ).
(Nice to see people reading the spec.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With