If ([] == false) is true, why does ([] || true) result in []?

前端 未结 3 1526
情深已故
情深已故 2021-01-21 03:31

Was just doing some testing and I find this odd:

[] == false

Gives true, this makes sense because double equal only compares contents and not t

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 03:56

    Type conversion is not related to falsy and truthy values.

    What is truthy and what is falsy is defined by the ToBoolean function defined in the specs and [] is indeed truthy.

    On the other hand, [] == false returns true because of the type conversion that happens during the evaluation of the expression.

    The rules of type conversion say that for x == y

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

    ToNumber results in 0 for false so we're left with the evaluation of [] == 0. According to the same rules

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

    ToPrimitive results in an empty string. Now we have "" == 0. Back to our type conversion rules

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

    ToNumber results in 0 for "" so the final evaluation is 0 == 0 and that is true!

提交回复
热议问题