How do the JavaScript relational comparison operators coerce types? -
what rules apply javascript relational comparison operators when operands of different types?
for example, how true > null evaluated? can type developer console , gives result true, why?
i searched bit, didn't find blog posts explaining this, although there plenty explaining type coercion == , === comparison operators.
javascript relational comparison operator type coercion defined in javascript specification, in sections 11.8 11.8.5 describe operators, , sections 9.1 (toprimitive) , 9.3 (tonumber) describe process of coercing operands.
in short, 4 comparison operators (<, >, <=, , >=) best convert each operand number, compare numbers. exception when both operands strings, in case compared alphabetically.
specifically,
if argument
oobject instead of primitive, try convert primitive value callingo.valueof()or - ifo.valueofwasn't defined or didn't return primitive type when called - callingo.tostring()if both arguments strings, compare them according lexicographical ordering. example, means
"a" < "b","a" < "aa"both return true.otherwise, convert each primitive number, means:
undefined->nannull-> +0booleanprimitive type ->1iftrue,+0iffalsestring-> try parse number string
then compare each item you'd expect operator, caveat comparison involving
nanevaluatesfalse.
so, means following:
console.log(true > null); //prints true console.log(true > false); //prints true console.log("1000.0" > 999); //prints true console.log(" 1000\t\n" < 1001); //prints true var oval1 = { valueof: function() { return 1; } }; var oval0 = { tostring: function() { return "0"; } }; console.log(oval1 > null); //prints true console.log(oval0 < true); //prints true console.log(oval0 < oval1); //prints true
Comments
Post a Comment