Search code examples
javascriptoperatorscoercion

Why is undefined == undefined true but not undefined <= undefined?


In JavaScript this is true:

undefined == undefined

But this is false:

undefined <= undefined

At first I thought the <= operator included the first one, but I'm guessing it tries to cast it to a number and it fails, but I didn't find any documentation to back this up.


Solution

  • The <= operator coerces both operands into actual Numbers before performing the comparison if both operands are primitives -- while == does not.1 Abstract relational comparison is performed which is where this conversion actually happens. The operation ToNumber is performed on undefined which yields NaN (see the linked table). If you then look at steps 4c and 4d from Abstract relational comparison, if either operand of <= is coerced into NaN, then undefined is returned from Abstract relational comparison. Going back to the first link, you'll see in step 7:

    If r is true or undefined, return false. Otherwise, return true.

    Since Abstract relation comparison returned undefined, <= evaluates to false.

    Less formally, you can see your comparison like this:

    const first = Number(undefined); //or +undefined
    const two = Number(undefined); //this is NaN
    NaN <= NaN
    

    Since NaN == NaN is never true, nor is NaN < NaN, NaN <= NaN is false.


    1 undefined == undefined returns true based on the abstract SameValueNonNumber operation which is used with equality operators if both operads are the same value, but not numbers.