6

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?

asked Jan 10, 2014 at 10:17
1
  • 'true' is string, true is boolean i.e string == boolean Commented Jan 10, 2014 at 10:21

4 Answers 4

8
'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.
answered Jan 10, 2014 at 10:38
Sign up to request clarification or add additional context in comments.

1 Comment

Best (and simplest) explanation so far!
4

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

DontVoteMeDown
21.5k10 gold badges72 silver badges113 bronze badges
answered Jan 10, 2014 at 10:20

1 Comment

IMHO, this does not answer the question. The conversion of both operands is exactly following the specification and thg435's answer should be accepted.
4

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.

answered Jan 10, 2014 at 10:21

2 Comments

I don't think this is how this algorithm works here. The correct sequence of steps is 7-5-1.c.i.
@thg435 — Argh! I missed the Type(y) what with all the Type(x)s in there.
1

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.

answered Jan 10, 2014 at 10:25

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.