Skip to content
case, cond, if
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow

if is a macro — works as you'd expect, but case and cond are more idiomatic.

case matches a value against patterns:

case n do
    0 -> "zero"
    n when n > 0 -> "positive"
    _ -> "negative"
end

The _ is a catch-all. when clauses add guards.

cond is for arbitrary boolean conditions:

cond do
    n > 100 -> "large"
    n > 10 -> "medium"
    true -> "small"   # always-true catch-all
end

if/else for simple binary decisions:

result = if x > 0, do: "positive", else: "non-positive"

In Elixir, only false and nil are falsy. Everything else (including 0 and "") is truthy.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…