-3

In JS, it's not clear if '0' is truthy or falsy. So, we have :

Boolean('0') == true, because it's a non-empty string. But: ('0' == false)

The brain-itching starts from here : (!'0' == false)

And then so... ('0' == !'0') // What ?!?

At the beginning, willing to store a websocket stream into a Mysql DB, I needed to convert each field from a string to its primitive type. Using the double NOT operator to get booleans didn't produce the result I was expecting : (!!"1" == true) && (!!"0" == true)

Having my input string s, I finally came up with this working solution : !!+s

Or this one : (s == '1')

Nowan
  • 13
  • 2
  • why not check the value according to the table's description? for numbers use `isFinite` or the stronger `Number.isFinite`. – Nina Scholz Jul 08 '23 at 08:24
  • try '!0' instead of !'0'. With !'0' you're saying; the inverse of the string literal '0' which is indeed false. – Maurice Jul 08 '23 at 08:25
  • Non-empty strings are truthy, so `"0"` is truthy since it's a string with contents. The number `0` is falsy though (using `== false` isn't a valid way to check if something is truthy/falsy, `!!` or `Boolean` is better) – Nick Parsons Jul 08 '23 at 08:25
  • `'0' == false` due to type coercion (I think) – Jaromanda X Jul 08 '23 at 08:31
  • any non-empty string is truthy value – Bhojendra Rauniyar Jul 08 '23 at 08:36
  • See [In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?](https://stackoverflow.com/questions/7615214/in-javascript-why-is-0-equal-to-false-but-when-tested-by-if-it-is-not-fals) – Ivar Jul 08 '23 at 08:41
  • Conclusion: never use `==` in JavaScript, but only `===` That should stop the itching. – trincot Jul 08 '23 at 09:04

1 Answers1

0

Is '0' truthy?

'0' is truthy, because non-empty strings are truthy

'0' == false is truthy, because == operator converts both operands to number first and then try to compare them. '0' is converted to 0 and false is converted to 0

(!'0' == false) - here !'0' is the same as !true because a non-empty string is truthy

('0' == !'0') - first !'0' is converted to !true then false and then both operands are converted to number so 0 == 0 is true

If you want intuitive behaviour don't use ==. Use === instead

Conclusion:

'0' is falsy, but == operator converts strings to numbers

About (!!"1" == true) && (!!"0" == true):

Isn't it easier to use:

const s = '1'
const boolean = s === '1'

?

Konrad
  • 21,590
  • 4
  • 28
  • 64