This small portion of code took a long time to be noticed.
I thought if I do the following, it would be fine
if('true' == true) {
alert("Does not happen");
}
But it does not pass the if condition.
I thought the double equals ==
matches the value not the type as matching the type is the job of ===
.
Now my questions are why wasn'the true
typecast to 'true'
or why is it checking for the type of these operands?
'true' == true
This is what happens here (according to the rules):
-- convert boolean to a number (rule 7):
'true' == 1
-- convert 'true' to Number (rule 5):
Number('true') == 1
-- Number('true')
is NaN
:
NaN == 1
-- return false (rule 1.c.i)
==
is indeed confusing, but it makes some sense once you understand the rules:
The ==
of Javascript is one of the worst part of the language that is build under no comprehensible logic... We suffer an old spec, that's just the answer.
Take a loot at the complete Facepalm:
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Sameness
edit for the edit
Yeah, the 'typecast' is not working as we could expect... there is no other answer.. :/
See the rules for ==
.
Type(x)
is a string and Type(y)
is a boolean. So Step 7 applies. It converts the boolean to a number and compares it to the string. The string you have won't match any number.
in JavaScript boolean, The result is 1 if the argument is true. The result is +0 if the argument is false. So, 'true' == true
is equivalent to 'true' == 1
which is of course, 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