8

I am still learning the basics of javaScript and I don't understand why this happens.

Having type coercion false == "false"would be converted into:

false == false //true

or

"false" == "false" //true

So, why false == "false" is false?

viery365
  • 797
  • 9
  • 26

4 Answers4

25

You've misunderstood the type conversion rules. false doesn't get converted to a string before comparison.

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

false is converted to a number, which gives:

+0 == "false"

… then …

If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

"false" is converted to a number, which gives:

+0 == NaN

… which is false.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • Is this answer I was looking for. I must understand better the rules of type coercion. Of course I am thinking always to use === but I needed to understand this. Thank you:) I will accept the answer in few minutes. – viery365 Aug 07 '16 at 12:46
  • 2
    And hence false === "0" would result into true. – sahaj Aug 07 '16 at 12:48
  • @sahaj Thank you!:) Yes, now I understand:) – viery365 Aug 07 '16 at 12:51
  • 3
    @sahaj - Not with `===` it won't. – nnnnnn Aug 07 '16 at 12:55
  • 2
    Yes, excuse me for the typo error. It should be ==. i.e. false == "0" would result into true. – sahaj Aug 07 '16 at 13:00
  • @nnnnnn Oh yes, using == of course, I didn't notice it:) – viery365 Aug 07 '16 at 13:01
  • @Quentin How does ToNumber("string") gets converted to NaN ? More importantly, how can I check this in a console ? Is there a way ? – Flying Gambit Aug 07 '16 at 13:07
  • @FlyingGambit — The short answer is "because that is what the spec says" (and I linked to the spec in the answer). You can't really check that in the console because it happens in the middle of the processing of a single operator. You can only see what happens at the two ends. (You could manually convert to a number with `+"false"` and see `NaN` though). – Quentin Aug 07 '16 at 13:09
  • @Quentin I think I got it, its basically like comparing between `+false == +"false"` which is the same as `0 == NaN`, this according to ECMA rules returns `false`. – Flying Gambit Aug 07 '16 at 13:14
5

The answer is because "false" is a string (as Gerardo Furado pointed out in the comments), the test you are making is equivalent to false = "hello".

Javascript does not look at the word in the string to determine if it is a boolean and then try to get the value from that.

Note:

In general in javascript it is now preferred that you use the === operator, to avoid all of this.

nycynik
  • 6,712
  • 5
  • 54
  • 80
0
false == "false" // false

because, the boolean false is converted into 0, so, we compare 0 with "false" and the output is false

Mansi Teharia
  • 670
  • 6
  • 10
-3

These are different kind of items. "string" and boolean.

So:

false.toString() == "false"
arturas
  • 676
  • 1
  • 5
  • 19