In javascript, String(true) == "true"
evaluates to true, and Boolean("true") == true
evaluates to true, so why does "true" == true
evaluate to false?
In javascript, String(true) == "true"
evaluates to true, and Boolean("true") == true
evaluates to true, so why does "true" == true
evaluate to false?
- 1 not following your logic...why should it? – blockhead Commented Jul 3, 2017 at 19:58
- 3 Because JavaScript? – Heretic Monkey Commented Jul 3, 2017 at 19:58
-
3
maybe you get confused using
Boolean("true")
, sinceBoolean("false")
also returns true. – Ulysse BN Commented Jul 3, 2017 at 19:59 - Per the Boolean docs at MDN: "If the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. If the DOM object document.all is passed as a parameter, the new boolean object also has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true." – j08691 Commented Jul 3, 2017 at 20:00
- 1 Note, that you've thrown the result of the type coersion away. – Teemu Commented Jul 3, 2017 at 20:01
2 Answers
Reset to default 9In "true" == true
the coercion is to number. So this bees:
NaN == 1
... which is false
.
The loose equality operands table on mozilla might be useful to check out.
Take a look to the MDN (Mozilla Developer Network). When we pare two operands of differents types, [the Abstract Equality Comparison Algorithm] will attempt to convert them to the same type before making the parison.
Finally, the answer is the following:
If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.
Then
When paring a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
So, finally, we pare Nan == 1
which is false
as pointed by @trincot.