admin管理员组

文章数量:1333402

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?

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?

Share Improve this question edited Jul 14, 2011 at 18:53 sth 230k56 gold badges287 silver badges370 bronze badges asked Jul 13, 2011 at 9:41 SachaSacha 2011 silver badge3 bronze badges 3
  • 5 +1 for quoting the spec in a question. :-) – RobG Commented Jul 13, 2011 at 9:47
  • 3 You should definitely look into false/NaN/0/undefined/""/null problems of Javascript. It's horribly inconsistent and one of most serious flaws of this (otherwise quite nice) language. – SF. Commented Jul 13, 2011 at 9:48
  • @SF: And if it had been really strict, people would plain about that instead. :-) The rules aren't really all that bad, and in fact this particular example has nothing to do with the false/NaN/0/undefined/""/null thing. It's more that the specification has this section saying how relations work, but you then have to look elsewhere to see that having done the work in the quoted section, there's more that the actual operator does. – T.J. Crowder Commented Jul 13, 2011 at 9:55
Add a ment  | 

1 Answer 1

Reset to default 15

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:

  1. Let lref be the result of evaluating RelationalExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating ShiftExpression.
  4. Let rval be GetValue(rref).
  5. Let r be the result of performing abstract relational parison lval < rval. (see 11.8.5)
  6. If r is undefined, return false. Otherwise, return r.

This is true of all of the relational operators. The algorithm has an undefined oute, 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.)

本文标签: Why is (1 lt NaN) false in JavaScriptStack Overflow