Search code examples
javascriptarrayscomparison-operatorscoercion

Why [null, undefined, []] == ",," returns true


I know that abstract comparison will convert LHS to String and String([null, undefined, []]) will result to ',,'.

But String(null) is 'null' and String(undefined) is 'undefined'. So how String([null, undefined, []]) is ',,'?


Solution

  • That's because.

    1. That's how == is defined https://tc39.es/ecma262/#sec-abstract-equality-comparison See step 11: If Type(x) is Object and Type(y) is either String, Number, BigInt, or Symbol, return the result of the comparison ? ToPrimitive(x) == y.
    2. Then ToPrimitive happens: https://tc39.es/ecma262/#sec-toprimitive
    3. Then OrdinaryToPrimitive happens: https://tc39.es/ecma262/#sec-ordinarytoprimitive which calls Array.prototype.toString
    4. For arrays it calls Array.prototype.join(arr) See https://tc39.es/ecma262/#sec-array.prototype.tostring
    5. That's how Array.prototype.join is implemented: https://tc39.es/ecma262/#sec-array.prototype.join, the most important steps:
    Repeat, while k < len,
    
    * If k > 0, set R to the string-concatenation of R and sep.
    * Let element be ? Get(O, ! ToString(k)).
    * If element is undefined or null, let next be the empty String; otherwise, let next be ? ToString(element).
    * Set R to the string-concatenation of R and next.
    * Set k to k + 1.