Reputation: 201
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?
Upvotes: 20
Views: 319
Reputation: 1074038
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.)
Upvotes: 15