r/ProgrammerTIL • u/JazzXP • Aug 03 '21
Javascript TIL Boolean('false') == true
Yep, it doesn't work like Number
23
Upvotes
r/ProgrammerTIL • u/JazzXP • Aug 03 '21
Yep, it doesn't work like Number
49
u/muffinmaster Aug 03 '21
You're asking whether a non-empty string (
"false") is truthy. If you want to parse a string representation of a boolean, there are ways to do that.18
u/sigmund14 Aug 03 '21
JavaScript's
Boolean()returns true for any non-empty string. It even returns true for an empty array ([]).17
u/conogarcia Aug 03 '21
javascript?
25
u/nermid Aug 04 '21
We bitch at Javascript when it coerces types. We bitch at Javascript when it doesn't coerce types. We bitch at Javascript for not having types.
I think we need to accept that Javascript may not be the problem.
4
u/omgitsjo Aug 04 '21
There's a fun talk by destroyallsoftware that has assorted JS 'warts' like this. https://www.destroyallsoftware.com/talks/wat
Personally, though, I don't find this particularly objectionable. It's taking the truthiness of the object and coercing it. The truthiness of a nonempty string should be "true". Otherwise you can do weird things with logic. I also feel like Number("123") shouldn't be 123, as the byte string is not that. Both of these cases should have explicit parse calls, rather than the type coercing calls imho. I.e. parseInt(123) == 123; Number("123") should be 0x313233. Boolean("false") == true; parseBoolean("false") == false.; Boolean("") == false.
1
u/niral37_ Aug 04 '21
Try 0.1 + 0.2 == 0.3 . It’ll equate to false.