Why does not the true match 'true' with double equals sign '==' in JavaScript? [duplicate]

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?

Answers:

Answer
'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:

  • garbage is equal to garbage (undefined == null)
  • no booleans (they're compared as numbers)
  • if one of the parts is a number, compare numeric
  • if one of the parts is a string, compare as strings
  • otherwise, a and b must be the same thing.
Answer

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.. :/

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.

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.