Boolean Operators

Boolean operators help to control logical flow within your program. They perform operations on boolean values and return a boolean result (true or false). The primary boolean operators are and, or, and not.

  • and: The and operator returns true if both the operands are true. Otherwise, it returns false.

    iex> true and true
    true
    
    iex> true and false
    false
  • or: The or operator returns true if at least one of the operands is true.

    iex> false or true
    true
    
    iex> false or false
    false
  • not: The not operator returns the opposite boolean value of the operand.

    iex> not true
    false
    
    iex> not false
    true
Elixir does not provide an xor infix operator. For exclusive-or on booleans, use a != b (two booleans are "xor true" exactly when they differ). If you need it spelled out, :erlang.xor/2 works too.
iex> true != false
true

iex> :erlang.xor(true, true)
false

Short-Circuit Operators

In addition to the boolean operators and, or, and not, Elixir provides &&, ||, and ! as equivalent short-circuit operators. Short-circuit evaluation, also known as minimal evaluation, is a method of evaluation in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression.

However, these operators handle non-boolean values differently than their counterparts, which is important to understand to avoid unexpected behavior in your Elixir programs.

  • && operator: This operator returns the first value if it is falsy (either false or nil). Otherwise, it returns the second value. This is why it only evaluates the second argument if the first one is truthy.

    iex> nil && true
    nil

    In the above example, nil && true returns nil because nil is a falsy value.

  • || operator: This operator returns the first value if it is truthy. Otherwise, it returns the second value. It only evaluates the second argument if the first one is falsy.

    iex> true || "Hello"
    true

    In this example, true || "Hello" returns true because true is a truthy value.

  • ! operator: This operator negates the truthiness of the value. It returns false for all truthy values and true for all falsy values.

    iex> !1
    false

    Here, !1 returns false because 1 is considered a truthy value in Elixir.