Falsy and Truthy

What are truthy and falsy?

A truthy is a value that will evaluate as true in a boolean context, while a falsy is a value that is equivalent to false.

When available in a programming language, using falsy and truthy can help write short and efficient conditions.

The only languages I know that use those expressions are interpretated one, but as I don't know all the programming languages in the universe

JavaScript

In javascript any value that is not a falsy is a truthy.

Available falsy are:

  • false
  • null
  • undefined
  • 0
  • NaN (Not a number)
  • '' (empty string)

That is to say if you already know that when existing a value is a string, you can check it exists and it isn't empty using a simple check

if (myText) {
    // code to execute if my text is not a falsy, that is to say it is neither undefined nor empty
}

Unfortunately in javascript an empty array is not a falsy.

Python

Like for javascript any value that is not a falsy is a truthy.

Available falsy are:

  • False
  • None
  • Any number equals to 0
  • Any empty collection:
    • [] / empty list
    • {} / empty dict
    • () / empty tuple
    • empty set
  • '' empty str
  • b'' empty bytes
  • empty range

objects with a method __bool__() returning False or a method __len__() returning 0.

Should you use them?

Some says yes (with caution), some says a big no.

I think that if you are sure of the different types of value your variable can take and if there is no risk of a falsy masking another one, you can use them.

Example of falsy masking an other one :

  • using a simple falsy test when an empty string is acceptable,
  • using a simple falsy test when the integer value 0 is acceptable.

Example of falsy check mistakes because of bad variable type:

  • check if we have a non empty string when the variable can be a boolean,
  • check if we have a non null property when it can be a 0 integer.

If your intended check was to check your value wasn't equivalent to a falsy… directly use a falsy!

I used to write things like:

if myVar is not None:
    #do something

if len(myArray) > 0:
    #do something

Now I will write:

if myVar:
    #do something

if myArray:
    #do something