Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 48 ยท Core Language

Conditionals: if, unless, cond and case

Choose between branches in Elixir with if, unless, cond, case and with. Learn truthiness, patterns in case, guards and how with chains steps.

Every program needs to make decisions. Elixir gives you four main tools, and each fits a different shape of problem: if and unless for one condition, cond for a list of conditions, case for matching one value against patterns, and with for a chain of steps that can each fail.

The first thing to know is that all of them are expressions. They return a value, so you can bind the result to a variable or return it from a function. The second is truthiness, from Operators and Comparison: only nil and false count as false. Everything else, including 0 and "", is true. The examples are read-only Elixir; the stand-ins at the end are JavaScript models, not real Elixir.

Pick the right tool

if / unless One condition, two outcomes.
cond Several different conditions.
case Match one value to patterns.
with Chain steps that may fail.

Every one of them returns a value.

1 / 2

if and unless

ELIXIR
temperature = 31

message =
  if temperature > 30 do
    "hot"
  else
    "fine"
  end
# "hot"

The else branch is optional. Without it, a false condition makes the whole if return nil. A short one-line form uses keyword arguments:

ELIXIR
if temperature > 30, do: "hot", else: "fine"

unless is the mirror image: it runs its block when the condition is falsy. Recent Elixir releases discourage it (and may warn about it), and it never has an else that reads well. Prefer if with a negated condition:

ELIXIR
if not logged_in do
  "please sign in"
end

There is no else if in Elixir. When you have more than two outcomes, switch to cond or case.

cond

cond evaluates conditions from top to bottom and runs the body of the first one that is truthy:

ELIXIR
score = 72

grade =
  cond do
    score >= 90 -> "A"
    score >= 80 -> "B"
    score >= 70 -> "C"
    true -> "needs work"
  end
# "C"

The final true -> clause is a catch-all. Without it, if no condition matches, Elixir raises a CondClauseError. Use cond when each branch tests a different expression. If every branch tests the same value, case reads better.

case

case takes a value and tries to match it against patterns, top to bottom. This is where the pattern matching from Pattern Matching: The = Operator pays off:

ELIXIR
result = {:ok, 42}

case result do
  {:ok, value} -> "got #{value}"
  {:error, reason} -> "failed: #{reason}"
  _ -> "something else"
end
# "got 42"

The first matching clause wins, and variables in the pattern are bound inside that clause. The underscore _ matches anything and is the usual catch-all. If nothing matches, you get a CaseClauseError, which is often what you want: an unexpected shape should crash loudly.

Guards

Add a when guard to a clause for extra conditions that patterns cannot express:

ELIXIR
case {:ok, 150} do
  {:ok, n} when n > 100 -> "big"
  {:ok, n} when n > 0 -> "small"
  {:ok, _} -> "zero or negative"
  {:error, _} -> "error"
end
# "big"

Only a limited set of functions is allowed in guards (comparisons, arithmetic, type checks such as is_integer/1, is_binary/1, length/1, in). A guard that raises simply makes the clause not match. Guards get a full lesson in Multiple Clauses and Guards.

The pin operator

A variable in a pattern normally binds. To match against an existing value, pin it with ^:

ELIXIR
expected = 5

case 5 do
  ^expected -> "same as expected"
  other -> "different: #{other}"
end

with

Sometimes you must do several steps, and each one may fail. Nested case expressions get ugly fast. with flattens them:

ELIXIR
def create_order(params) do
  with {:ok, user} <- find_user(params.user_id),
       {:ok, item} <- find_item(params.item_id),
       :ok <- check_stock(item) do
    {:ok, %{user: user, item: item}}
  else
    {:error, :not_found} -> {:error, "unknown user or item"}
    {:error, reason} -> {:error, reason}
  end
end

Each pattern <- expression line runs in order. If the value matches, the variables are bound and the next line runs. As soon as one value does not match, with stops and either returns that value as it is (no else) or tries the else clauses, which work like case. If everything matches, the do block runs. This is the standard way to write "happy path" code, and Error Handling: Tuples, with and Exceptions builds on it. The helper functions above are made up for the example.

JavaScript stand-ins

Real Elixir cannot run here, so these editors model the decision rules in JavaScript. First, case and cond as functions: clauses are tried in order, an unmatched value raises, and guards are plain functions.

JS case and cond (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the clause order matters: 150 also satisfies n > 0, but the n > 100 clause comes first and wins.

Second, with as a function that stops at the first value that fails to match.

JS with chains (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does if false, do: 1 return?

    Without an else branch, a false condition makes if return nil.
  2. 2. What happens in a cond when no condition is truthy and there is no true -> clause?

    cond requires some clause to match, so add true -> as the last clause for a default.
  3. 3. In case {:ok, 5} do {:ok, n} when n > 10 -> :big; {:ok, _} -> :small end, what is returned?

    The first clause matches the pattern but its guard n > 10 is false, so the next clause matches.
  4. 4. What does with do when a <- step does not match and there is no else?

    with stops at the first non-matching value and returns it unchanged, which makes {:error, reason} flow through easily.
  5. 5. Which values are falsy in Elixir?

    Only nil and false are falsy. Zero, the empty string and the empty list are all truthy.

Summary

  • if, cond, case and with are expressions that return a value; there is no else if.
  • Only nil and false are falsy.
  • cond runs the first truthy condition and needs a true -> catch-all.
  • case matches a value against patterns top to bottom, with optional when guards and ^ pins; no match raises CaseClauseError.
  • with chains pattern <- expression steps and stops at the first mismatch, optionally handled by else.
  • Prefer case over if chains when you are inspecting the shape of data.

Next up: Functions and Modules.