Federico Sawady
Federico Sawady

Reputation: 900

Why !"0" == "0" is true?

I'm working with JavaScript and I had this bug, the cause was that "0" and !"0" entered in the "then" sentence. When I tried in a console I saw:

!"0" == "0" -> true

Why did this happen?

Upvotes: 0

Views: 131

Answers (4)

khizerrehandev
khizerrehandev

Reputation: 1525

This is why JavaScript coercion is tricky and plays very handy part specifically in case of 0 number which is 99% the bug cause.

  • When Equality (==) comparison is applied on two values e.g x == y by default comparison value is checked from L->R (left to rigth).

  • So In your case before Loose (==) equality is checked the ! (negation is applied) which results !"0" -> false.

  • Now comes the coercion part: According to ECMAScript ecma-262 specs it states

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

      OR

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

Which means if either of the value is in Boolean like in our case

-> false == "0"

-> Number(false) == "0"

-> Number(false) == Number("0")

-> 0 == 0 // Results into truthy values;

Therefore:
!"0" == "0" -> true

Upvotes: 0

CRice
CRice

Reputation: 32146

!"0" converts the string "0" into a boolean, and takes its negation. So since "0" is truthy (the only falsy string is the empty string), its negation is the boolean value false. So to be clear:

!"0" is converted to false.

Since we are comparing the boolean false with the string "0", javascript will convert both values to numbers. See the table in this documentation to see which types, when compared, are converted to what. You'll note that for a boolean and string, both are changed to numbers and then compared.

So wrapping up, we have !"0", which evaluates to false. Then we compare that to the other string: "0". Because one is a boolean, and the other a string, they are converted to numbers. The number conversion for false is 0, and the number conversion for "0" is 0, which are equal. Thus we get the result you see.

Upvotes: 3

Axnyff
Axnyff

Reputation: 9944

!"0" will convert "0" to false and then false is == to "0" because they will both be converted to the integer 0. https://stackoverflow.com/a/7615326/4949918

Upvotes: -1

rollstuhlfahrer
rollstuhlfahrer

Reputation: 4078

One would say, its javascript. There is a logical explanation:

  • !"0" evaluates to false
  • "0" will be casted to 0 which is equal to false

Since you are now comparing false and false, they are both the same. Your comparison has to be true.

Upvotes: 0

Related Questions