Elixir Truthiness - Understand Falsy and Truthy Values

Understand Elixir

Elixir Truthiness

Understanding Elixir Truthiness

In Elixir, the concept of "truthiness" dictates how values are evaluated in boolean contexts, such as within conditional statements. Understanding these rules is fundamental for writing correct and predictable Elixir code.

Falsy Values in Elixir

Elixir defines specific values as "falsy," meaning they are treated as false in boolean evaluations. The primary falsy values are:

  • :nil: This atom represents the absence of a value.
  • :false: This atom explicitly represents the boolean value false.

It's important to note that nil and false (without the colons) are syntactic sugar in Elixir. When you use nil or false, Elixir interprets them as their atom equivalents, :nil and :false, respectively, in truthiness checks.

Truthy Values in Elixir

By definition, any value in Elixir that is not explicitly falsy is considered "truthy." This means that all other atoms, integers, floats, strings, lists, maps, structs, and any other data types will evaluate to true in a boolean context.

Practical Examples

The following examples demonstrate how truthiness works in Elixir:

> !!nil
# false
> !!false
# false
> !!:nil
# false
> !!:false
# false
> !!0
# true
> !!""
# true
> !![]
# true
> !!1
# true

> nil || :nil || false || :false || 1
# 1
> nil || :nil || false || :false || "hello"
# "hello"

In the last example, the expression evaluates from left to right. Since nil, :nil, false, and :false are all falsy, the `||` (or) operator continues to the next value. When it encounters 1 (which is truthy), the expression short-circuits and returns 1. Similarly, if it encounters a truthy string like "hello", that value is returned.

Key Takeaways for Developers

When working with Elixir, remember that only nil and false (and their atom equivalents :nil and :false) are falsy. This simplifies conditional logic, as you don't need to worry about other data types being implicitly treated as false.

Further Reading