Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 668
me_digvijay Avatar asked Jan 10 '14 10:01

me_digvijay


4 Answers

'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.
like image 70
georg Avatar answered Oct 08 '22 22:10

georg


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

like image 32
farvilain Avatar answered Oct 08 '22 20:10

farvilain


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.

like image 31
Quentin Avatar answered Oct 08 '22 22:10

Quentin


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.

like image 23
Claies Avatar answered Oct 08 '22 21:10

Claies