🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Boolean Logic

Boolean logic combines true and false values into one result. Elixir has strict operators that need booleans and relaxed operators that accept any value.

Strict and, or and not

The strict operators combine boolean values. Each line below prints one combined result.

IO.puts(true and false)
IO.puts(true or false)
IO.puts(not true)

Relaxed operators return values

The || operator returns the first truthy value it meets. The && operator returns a value too, not just true or false.

IO.puts(nil || "fallback")
IO.puts(true && "yes")
IO.puts(false || 42)

Truthiness with the bang operator

The ! operator flips a value by its truthiness. Only nil and false flip to true.

IO.puts(!0)
IO.puts(!nil)
IO.puts(!false)
IO.puts(!"text")

Example

logged_in = true
has_ticket = false
age = 20
nickname = nil
IO.puts(logged_in and has_ticket)
IO.puts(logged_in or has_ticket)
IO.puts(age >= 18 && logged_in)
IO.puts(nickname || "guest")

Key points

  • Strict family: and, or and not expect a boolean value on each side.
  • and: the result is true only when both sides are true.
  • or: the result is true when at least one side is true.
  • not: not flips true to false and false to true.
  • Relaxed family: &&, || and ! accept values of any type.
  • Falsy values: only nil and false count as falsy in Elixir.

In this example, and gives false because the visitor has no ticket, while or gives true because the visitor is logged in. The && check passes for an adult who is logged in, and || replaces the missing nickname with guest.

Note

0 and an empty string are truthy, unlike in some other languages.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does nil || "guest" return?