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:
isNaN(Number("true")) // true)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?
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.
Because == (and === ) test to see if two objects are the same object and not if they are identical objects.
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 ."
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.
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 == comparison operator is defined in ECMA 5 as:
So, "true" == true is evaluated as:
===> false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With