If

If in Elixir

51 exercises

About If

Besides cond, Elixir also provides the macro if/2 which is useful when you need to check for only one condition.

if/2 accepts a condition and two options. It returns the first option if the condition is truthy, and the second option if the condition is falsy.

age = 15

if age >= 16 do
  "You are allowed to drink beer in Germany."
else
  "No beer for you!"
end

# => "No beer for you!"

If the second option is not given, nil will be returned.

age = 15

if age >= 16 do
  "You are allowed to drink beer in Germany."
end

# => nil

It is also possible to write an if expression on a single line. Note the comma after the condition.

if age >= 16, do: "beer", else: "no beer"

This syntax is helpful for very short expressions, but should be avoided if the expression won't fit on a single line.

Truthy and falsy

In Elixir, all datatypes evaluate to a truthy or falsy value when they are encountered in a boolean context (like an if expression). All data is considered truthy except for false and nil. In particular, empty strings, the integer 0, and empty lists are all considered truthy in Elixir. In this way, Elixir is similar to Ruby but different than JavaScript, Python, or PHP.

truthy? = fn x -> if x, do: "truthy", else: "falsy" end

truthy?.(true)
# => "truthy"
truthy?.(0)
# => "truthy"
truthy?.([])
# => "truthy"

truthy?.(false)
# => "falsy"
truthy?.(nil)
# => "falsy"

&&/2, ||/2, and !/1 are truthy boolean operators which work with any value, which complement the strict boolean operators and/2, or/2, and not/1.

0 and true
# => ** (BadBooleanError) expected a boolean on left-side of "and", got: 0

0 && true
# => true
Edit via GitHub The link opens in a new window or tab

Learn If

Practicing is locked

Unlock 1 more exercise to practice If