Search code examples
javascriptcoercion

Coercion in JavaScript


I was wondering a few things about coercion.

When you do:

1 == true // true

Which one is coerced into which one ? is it the left one or the right one ?

When you do

undefined == null // true

How does it work exactly ? In which order does it try to convert it ? By instance:

1)    String(undefined) == String(null) // false
2)    Number(undefined) == Number(null) // false
3)    Boolean(undefined) == Boolean(null) // true

Does it first try to coerce the left side operand ? then the right ? then both ?

EDIT: As explained in the comments: "not a duplicate. While both questions are about type coercion, this one asks which operand get coerced into the other. The other one is about the source of truth when evaluating the coerced types"


Solution

  • The process is described at 7.2.12 Abstract Equality Comparison:

    The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

    1. If Type(x) is the same as Type(y), then return the result of performing Strict Equality Comparison x === y.

    2. If x is null and y is undefined, return true.

    3. If x is undefined and y is null, return true.

    4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

    5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.

    6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

    7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

    8. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then return the result of the comparison x == ToPrimitive(y).

    9. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison ToPrimitive(x) == y.

    10. Return false.

    So rather than coercing one side and then the other, or something like that, it's more that the interpreter goes through that list above until it finds a matching condition, and executes the resulting command, which may involve coercing only the left side, or only the right side (and, rarely, both, in case a recursive command is reached, such as with true == '1', which will fulfill condition 8, turn into 1 == '1', fulfilling condition 6 and turning into 1 == 1, fulfilling condition 3 and resolving to true)