🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir If and Unless

An if expression chooses a value by testing a condition. The chosen value can be stored in a variable like any other value.

A true test returns the do value

The short form of if fits on one line. The test runs first, and only the matching value is returned.

score = 82
label = if score >= 60, do: "pass", else: "fail"
IO.puts(label)

A false test returns the else value

The block form spreads the same choice over several lines. It suits longer values that would crowd one line.

age = 15
message =
  if age >= 18 do
    "adult ticket"
  else
    "youth ticket"
  end
IO.puts(message)

Unless picks its do value when the test is false

Unless reads as if not. Here the test is false, so the do value wins.

raining = false
plan = unless raining, do: "walk outside", else: "stay inside"
IO.puts(plan)

Example

age = 20
ticket =
  if age >= 18 do
    "adult"
  else
    "youth"
  end
member = false
extra = unless member, do: "guest pass", else: "member pass"
IO.puts(ticket)
IO.puts(extra)

Key points

  • Condition: the true-or-false test that an if expression checks first.
  • Do value: the value an if returns when its condition is true.
  • Else value: the value an if returns when its condition is false.
  • Missing else: an if with no else returns nil when its condition is false.
  • Block form: a long if writes do and else on separate lines and ends with end.
  • Unless: a reversed if that returns its do value when the condition is false.

In this example, the if test passes because age is 20, so ticket holds the do value. The unless test is false because member is false, so extra holds its do value too.

Note

only false and nil fail an if test, and every other value passes it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

With score = 30, what does label hold after label = if score >= 60, do: "pass", else: "fail"?