Search code examples
javascriptecmascript-6primitivecomparison-operatorsinfinity

Why does Javascript not follow ECMA specs on Infinity/NaN comparisons?


I have tested in Chrome, Firefox, Safari. They all give the same results on these comparisons.

  • 0 < NaN returns false.
  • Infinity < Infinity returns false.
  • -Infinity < -Infinity returns false.

While according to the Abstract Relational Comparison algorithm, in the 4h and 4i steps, the above expressions should return undefined, true, true.

What am I missing here?

enter image description here


Solution

  • lval < rval, when evaluated, does:

    1. Let r be the result of performing Abstract Relational Comparison lval < rval.
    2. ReturnIfAbrupt(r).
    3. If r is undefined, return false. Otherwise, return r.

    Although "Abstract Relational Comparison" (ARC) may return undefined, the final result of the evaluation of the < operator is always true or false.

    The actual comparison of numbers to other numbers is shown in 6.1.6.1.12 Number::lessThan ( x, y ); see how ARC says:

    f. If Type(nx) is the same as Type(ny), return Type(nx)::lessThan(nx, ny).

    So nothing below step F in ARC is relevant for these expressions you're checking, because in each of the expressions, you're comparing a number to another number.


    0 < NaN fulfills step 2 of lessThan:

    If y is NaN, return undefined.

    resulting in ARC returning undefined, resulting in a final value of false: If r is undefined, return false..

    Infinity < Infinity first fulfills step 6, which is:

    If x is +∞, return false.

    -Infinity < -Infinity first fulfills step 8, which is:

    If y is -∞, return false.