Search code examples
javascripttypesecmascript-5coerciontype-coercion

The Abstract Relational Comparison Algorithm: Why evaluation order is important?


When I read EcmaScript spesification in The Abstract Relational Comparison Algorithm part have information about "LeftFirst" parameter and also spesification say evauation order is not important primitive type but important Object type. Anyone can explain me what is difference which object first evaluated?

http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 Ecmascript Spesification (aka ecma-internation.org) section 11.8.5 (The Abstract Relational Comparison Algorithm)


Solution

  • The Abstract Relational Comparison Algorithm evaluates x < y, but it is used for several operators, E.G. x < y, x > y, x >= y, sometimes by flipping the order of the operands. In the case of x > y, the spec for the Greater-than operator says:

    Let r be the result of performing abstract relational comparison rval < lval with LeftFirst equal to false.

    LeftFirst doesn't matter for primitives because there are no side-effects when they are coerced to numbers for the comparison. However, for objects there can be side-effects:

    const x = { valueOf: _ => console.log( 'x' ) };
    const y = { valueOf: _ => console.log( 'y' ) };
    
    y > x;

    The above code logs y then x. Since it uses the greater-than operator, it uses the Abstract Relational Comparison Algorithm for x < y with LeftFirst = false as per the above quote from the spec. If instead it used the same algorithm, but with LeftFirst = true, then it would end up calling ToPrimitive on x before calling ToPrimitive on y, which would cause x to be logged before y.