Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why false == "false" is false?

Tags:

javascript

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?

like image 250
viery365 Avatar asked Aug 07 '16 12:08

viery365


3 Answers

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.

like image 66
Quentin Avatar answered Nov 13 '22 04:11

Quentin


false == "false" // false

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

like image 34
Mansi Teharia Avatar answered Nov 13 '22 06:11

Mansi Teharia


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.

like image 5
nycynik Avatar answered Nov 13 '22 05:11

nycynik