Truth And Consequences

Truth And Consequences

Yesterday I was in an all day meeting preparing for a large customer demonstration. Ran into a bug that turned out to be a misunderstanding of how JavaScript handles truthiness. Consider the following code:

if (person.address) {
  console.log('Address is ' + person.address);
}
else {
  console.log('No address.');
}

Seems clean enough right? Not so fast. If person.address is null, no problem. However, if person.address is an empty object, that evaluates to true, and the code fails to do the right thing. To me at least, this is non-intuitive behavior.

I started this blog with a discussion of why I love Python, and once again it behaves more intuitively. Empty dictionary, empty list, None, and empty string all evaluate to False. So the code works in a broader-variety of cases:

if person['address']:
    logging.info('Address is ' + person['address'])
else:
    logging.info('No address.')

Isn’t that nice and clean?

As an aside, most developers have become so accustomed to bracketing punctuation (e.g. braces, semicolons) that they assume there’s no other way. Personally I’ve come to love the lack of noise in Python syntax, and I think you will too.

One Reply to “Truth And Consequences”

  1. You can customize truthiness in your classes as well!
    “`
    >>> class Person():
    … def __init__(self, name: str, alive: bool = True):
    … self.name = name
    … self.alive = alive

    … def __bool__(self):
    … return all([self.name, self.alive])

    >>> george = Person(‘George’)
    >>> philbert = Person(‘Philbert’, alive=False)
    >>> blank = Person(”)
    >>> for person in (george, philbert, blank):
    … print(f”{person.name}’s Truthiness: {bool(person)}”)
    George’s Truthiness: True
    Philbert’s Truthiness: False
    ‘s Truthiness: False
    “`

Leave a Reply

Your email address will not be published. Required fields are marked *