r/programming • • Mar 26 '14

JavaScript Equality Table

http://dorey.github.io/JavaScript-Equality-Table/
809 Upvotes

331 comments sorted by

View all comments

17

u/MisterSnuggles Mar 26 '14

While not JavaScript, we must not forget about Python's False Midnight.

tl;dr:

if datetime.time(0,0):
    print "t"
else:    
    print "f"

Prints "f".

if datetime.time(1,0):
    print "t"
else:    
    print "f"

Prints "t".

12

u/[deleted] Mar 26 '14

Why do so many dynamic languages have this obsession with using non-boolean values in conditionals?

7

u/Nialsh Mar 26 '14

It can be a very short, readable way to validate inputs. In Python, I believe these are equivalent:

if name:

versus

if name != None and name != ""

6

u/NYKevin Mar 27 '14

No, those are not necessarily equivalent unless the type of name is known.

If name is a number, it will be falsey iff it is zero (None is not a number but a singleton instance of NoneType, which is always falsey). If name is a string, it is falsey iff it is empty. "0" is truthy because it is nonempty. "0" and 0 are very different things, and Python generally won't coerce between them unless you explicitly call int() or str(). Moving on, if name is a container type of some kind, generally speaking it is falsey iff it is empty (has a len() of zero). The empty string being falsey is a special case of this rule.

For user-defined types, you're on your own. By default they're all truthy, but you can't rely on that since someone might subclass you and implement non-default boolean semantics.

If you want to check whether something is None, the only bulletproof syntax for doing so is if foo is None or if foo is not None. if foo should only be used if foo has a non-default boolean behavior (i.e. foo is a container, number, string, or user-defined class which overrides bool()). Using if foo with classes which do not provide useful boolean behavior (such as datetime objects) is at best poor style and at worst a violation of substitutability since it would interfere with subclassing.

→ More replies (14)

1

u/[deleted] Mar 27 '14

Yeah, I think that could be handled by a function called "nonempty" or something. Including this logic in the if-statement itself is rather unorthogonal.