Why does "true" == true show false in JavaScript?

Acording to The Abstract Equality Comparison Algorithm

http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

if one of the oprends is a boolean and other is not, boolean is converter to number 0 or 1. so true == "true" is false.


The == comparison operator is defined in ECMA 5 as:

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

So, "true" == true is evaluated as:

  1. "true" == ToNumber(true)   (via rule 7)
  2. "true" == 1
  3. ToNumber("true") == 1   (via rule 5)
  4. NaN == 1

===> false


Because "true" is converted to NaN, while true is converted to 1. So they differ.

Like you reported, both are converted to numbers, because at least true can be (see Erik Reppen's comment), and then compared.


The equality operators (== and !=) use the Abstract Equality Comparison Algorithm to compare two operands.

"true" == true

Since "true" is String and true is Boolean, we need to return the result of "true" == Number(true) (step 7 in the algorithm), which is "true" == 1.

"true" == 1

Since "true" is String and 1 is Number, we need to return the result of Number("true") == 1 (step 5 in the algorithm). Number("true") returns NaN. Now we have NaN == 1.

NaN == 1

Now both operands are of the same type (Number). Acording to the algorithm, if both operands are Number and one of them is NaN, false is returned (step 1.c.i in the algorithm).