Why is true matching "true" with double equal to the "==" sign in JavaScript?

This small piece of code took a long time to be noticed.

I thought that if I did the following, it would be good

if('true' == true) { alert("Does not happen"); } 

But this does not pass the if condition.

I thought that double equals == corresponds to the value, and not to the type corresponding to the type - task === .

Now my questions is why wasn'the true typecast to 'true' or why does it check the type of these operands?

+6
source share
4 answers
 'true' == true 

Here's what happens here (according to the rules ):

- convert boolean to number (rule 7):

 'true' == 1 

- convert 'true' to Number (rule 5):

 Number('true') == 1 

- Number('true') NaN :

 NaN == 1 

- return false (rule 1.ci)

== really confusing, but it makes sense if you understand the rules:

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

== Javascript is one of the worst parts of the language, which is built under clear logic ... We suffer from the old specification, this is just the answer.

Take the loot on full Facepalm:

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Sameness

edit to edit

Yes, the “type” does not work, as we might expect ... there is no other answer ...: /

+4
source

See rules for == .

Type(x) is a string, and Type(y) is a boolean. Thus, step 7 is applied. It converts the logical value into a number and compares it with the string. The row you have will not match the quantity.

+4
source

in JavaScript boolean, the result is 1 if the argument is true. The result is +0 if the argument is false. Thus, 'true' == true equivalent to 'true' == 1 , which of course is false.

+1
source

All Articles