Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

MDC describes the == operator as follows:

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.

With this in mind, I would evaluate "true" == true as follows:

  1. Are they of the same type? No
  2. Is either operand a number or boolean? Yes
  3. Can we convert both to a number? No (isNaN(Number("true")) // true)
  4. Is either operand a string? Yes
  5. Can we convert the other operand to a string? Yes (String(true) === "true" // true)

I've ended up with the strings "true" and "true", which should evaluate to true, but JavaScript shows false.

What have I missed?

like image 555
Isaac Avatar asked Jul 06 '12 13:07

Isaac


People also ask

Why True == true is false in JavaScript?

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.

Why == is false in JavaScript?

Because == (and === ) test to see if two objects are the same object and not if they are identical objects.

Why does true == true return false?

Because they don't represent equally convertible types/values. The conversion used by == is much more complex than a simple toBoolean conversion used by if ('true') . So given this code true == 'true' , it finds this: "If Type(x) is Boolean , return the result of the comparison ToNumber(x) == y ."

What is the result of true == 1 in JavaScript?

Boolean type take only two literal values: true and false. These are distinct from numeric values, so true is not equal to 1, and false is not equal to 0.


2 Answers

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.

like image 95
MaxArt Avatar answered Sep 22 '22 14:09

MaxArt


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

like image 42
nobitavn94 Avatar answered Sep 18 '22 14:09

nobitavn94