Elixir Language Operators Boolean operators


Example

There are two kinds of boolean operators in Elixir:

  • boolean operators (they expect either true or false as their first argument)
x or y      # true if x is true, otherwise y

x and y     # false if x is false, otherwise y

not x       # false if x is true, otherwise true

All of booleans operators will raise ArgumentError if first argument won't be strictly boolean value, which means only true or false (nil is not boolean).

iex(1)> false and 1 # return false
iex(2)> false or 1 # return 1 
iex(3)> nil and 1 # raise (ArgumentError) argument error: nil
  • relaxed boolean operators (work with any type, everything that neither false nor nil is considered as true)
x || y     # x if x is true, otherwise y

x && y     # y if x is true, otherwise false

!x         # false if x is true, otherwise true

Operator || will always return first argument if it's truthy (Elixir treats everything except nil and false to be true in comparisions), otherwise will return second one.

iex(1)> 1 || 3 # return 1, because 1 is truthy
iex(2)> false || 3 # return 3
iex(3)> 3 || false # return 3
iex(4)> false || nil # return nil
iex(5)> nil || false # return false

Operator && will always return second argument if it's truthy. Otherwise will return respectively to the arguments, false or nil.

iex(1)> 1 && 3 # return 3, first argument is truthy
iex(2)> false && 3 # return false
iex(3)> 3 && false # return false 
iex(4)> 3 && nil # return nil
iex(5)> false && nil # return false
iex(6)> nil && false # return nil

Both && and || are short-circuit operators. They only execute the right side if the left side is not enough to determine the result.

Operator ! will return boolean value of negation of current term:

iex(1)> !2 # return false
iex(2)> !false # return true
iex(3)> !"Test" # return false
iex(4)> !nil # return true

Simple way to get boolean value of selected term is to simply double this operator:

iex(1)> !!true # return true
iex(2)> !!"Test" # return true
iex(3)> !!nil # return false
iex(4)> !!false # return false