-1

Today while reading a blog on JavaScript, I came across the below example which seems odd to me. Please clarify.

As per my JavaScript knowledge !!"0" results true

But, the below statement result seems odd to me, and even I executed it in console which also returned true

false == "0" //results true

My interpretation of this statement is as below

"0" is treated as true, so the above statement can be rewritten as false == true, which must be resulted as false, but I am getting true as result. Please clarify.

Azeez
  • 318
  • 3
  • 14
  • 3
    info you may want to look at https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons?rq=1 and https://stackoverflow.com/questions/7615214/in-javascript-why-is-0-equal-to-false-but-when-tested-by-if-it-is-not-fals – epascarello Jan 30 '19 at 17:53
  • `("0" == true) === false` – Heretic Monkey Jan 30 '19 at 17:54
  • 1
    As answered in https://stackoverflow.com/questions/7615214/in-javascript-why-is-0-equal-to-false-but-when-tested-by-if-it-is-not-fals, the reason is because when you explicitly do "0" == false, both sides are being converted to numbers, and then the comparison is performed. – Azeez Jan 30 '19 at 17:58

1 Answers1

3

When using ==, "0" is first type casted to it's number value, 0. And 0 == false.

When doing !!"0", it is not casted, and simply converts the string to a boolean, and since any non-empty string is truthy, it equals to true.

Charles Crete
  • 944
  • 7
  • 14