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,

  1. if argument o object instead of primitive, try convert primitive value calling o.valueof() or - if o.valueof wasn't defined or didn't return primitive type when called - calling o.tostring()

  2. if both arguments strings, compare them according lexicographical ordering. example, means "a" < "b" , "a" < "aa" both return true.

  3. otherwise, convert each primitive number, means:

    • undefined -> nan
    • null -> +0
    • boolean primitive type -> 1 if true, +0 if false
    • string -> try parse number string
  4. then compare each item you'd expect operator, caveat comparison involving nan evaluates false.

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

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -