A version of this article originally appeared on my GitHub pages blog
Different languages have different opinions about what to treat as "truthy" or "falsy" when using a non-boolean object as an expression inside an if
statement.
I looked at Python, Groovy, Javascript and Ruby to compare their differences.
- Null is always falsy
- Zero and empty strings are falsy, except in Ruby
- Empty collections (set/list/dict) are falsy in Python and Groovy but not Javascript or Ruby
My observations and personal opinions on language design:
- Python treats zero, empty strings and collections all as 'falsy'. Personally, I find this the most intuitive convention.
- Treatment of zero and null as falsy has historical precedent, from C. False and null pointers are both represented as zeros in a register or memory location.
- Treatment of empty strings and collections is a nice convenience, given the number of times I've written conditionals like
if (foo != null and !foo.empty())
. It's usually the exception that I want to distinguish between null and empty in a conditional. So it's nice thatif (foo)
handles the common case, then I can writeif (not foo is None)
when I really do want to distinguish null. - Treatment of empty string as similar to null feels familiar from my Oracle experience. Also, it's consistent with treatment of an empty collection.
- Groovy is inspired by Python and adopts similar conventions for truthiness.
- Ruby takes a different opinion that all values are truthy except
nil
(andfalse
, of course). While it's not my personal preference, it's defensible and self-consistent. - Javascript can reliably be expected to deliver a WTF. Javascript treats zero and empty strings as falsy, but empty collections as truthy. To me, it's hard to understand why strings and collections ought to behave differently; the Python behavior makes much more sense. But wait, it gets even better: check out this link on StackOverflow.
Top comments (3)
For me - but it's only an opinion - the very true is that only Booleans should be true. Of course, it's short to write, and I am lazy, too. I am using Pythonic truthiness very often. But how much more straightforward it is to treat true as true, and false as false. It would be more readable to use
string.is_empty()
orarray.no_elements()
.Are you arguing for static compile-time type checking in general, or specifically that if/while etc. should not accept non-boolean types?
I mean that it's more clear when we explicitly say: I am returning a boolean value. I am far from static type checking.