Booleans and nil
Elixir supports true and false as booleans.
true
false
Are they equal?
true == false
To operate on booleans, Elixir provides and/2, or/2 and not/1.
Logical and of two true values:
true and true
true or false
Note that and and or are short-circuit: if the left-hand side determines the result, the right-hand side won’t even be evaluated. It’s especially important when used expressions have side-effects.
# 💡 Try changing `true` to `IO.inspect(true)` to see if it gets evaluated.
false and true
Logical or:
false or is_boolean(true)
Logical not:
not true
The nil value
Elixir also provides the concept of nil, to indicate the absence of a value, and a set of logical operators that also manipulate nil: ||, &&, and !. For these operators, false and nil are considered “falsy”, all other values are considered “truthy”.
Using && with booleans:
true && false
nil is falsy, so && short-circuits:
# 💡 Try changing `&&` to `and`. What happens?
nil && 13
true is truthy, so && returns the right-hand side:
true && 17
|| returns the first truthy value:
# 💡 Try changing `1` to `IO.inspect("foo")`. Is "foo" printed out?
1 || true
false is falsy, so || returns the right-hand side:
false || 11
The ! operator:
# 💡 Try `!1` and `!nil`.
!true
As a rule of thumb, use and, or, and not when you are expecting booleans. If any of the arguments are non-boolean, use &&, ||, and !.