开发者

Why is (1 < NaN) false in JavaScript?

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?


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 comparison 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 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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜