What rules apply for the JavaScript relational comparison operators when the operands are of different types?
For example, how is true > null evaluated? I can type this into my developer console and it gives the result true, but why?
I searched for a bit, but didn’t find any blog posts explaining this, although there are plenty explaining type coercion for == and === comparison operators.
JavaScript relational comparison operator type coercion is defined in the JavaScript specification, specifically in sections 11.8 to 11.8.5 which describe the operators, and sections 9.1 (ToPrimitive) and 9.3 (ToNumber) which describe the process of coercing the operands.
In short, the 4 comparison operators (
<,>,<=, and>=) do their best to convert each operand to a number, then compare the numbers. The exception is when both operands are strings, in which case they are compared alphabetically.Specifically,
If an argument
ois an object instead of a primitive, try to convert it to a primitive value by callingo.valueOf()or – ifo.valueOfwasn’t defined or didn’t return a primitive type when called – by callingo.toString()If both arguments are Strings, compare them according to their lexicographical ordering. For example, this means
"a" < "b"and"a" < "aa"both return true.Otherwise, convert each primitive to a number, which means:
undefined->NaNNull-> +0Booleanprimitive type ->1iftrue,+0iffalseString-> try to parse a number from the stringThen compare each item as you’d expect for the operator, with the caveat that any comparison involving
NaNevaluates tofalse.So, this means the following: