All lessons

Making Decisions

7 min · Elixir

Run different code depending on whether something is true.

Elixir · Making Decisions0/5 cleared

Enemy 1 of 5

if / else syntax

Programs often need to act differently depending on their data. In Elixir, if checks a condition and runs one of two branches.

This code checks if the temperature is above 20 and prints Warm or Cold. Press Run to see which one it picks.

Why this works

Any program worth writing eventually needs to behave differently depending on its data: send a different response to a valid request than an invalid one, treat a large number differently than a small one. `if` is the most direct tool Elixir gives you for that: it evaluates a condition and runs one branch or another depending on whether that condition is true.

Elixir's `if` reads as `if condition do ... else ... end`. The `do`/`end` pair delimits a block, a pattern you'll see reused for many other constructs in Elixir (modules, functions, loops all use `do`/`end` similarly). If the condition is true, the `do` branch runs; otherwise the `else` branch runs. `else` is optional: if you omit it and the condition is false, the whole `if` simply evaluates to `nil` (Elixir's "nothing here" value).

Comparisons use the operators you'd expect: `>`, `<`, `>=`, `<=` for ordering, `==` for equality, and `!=` for "not equal." Unlike some languages, Elixir also lets you compare values of different types (like a number and a string) without raising an error (it has a well-defined, if occasionally surprising, ordering across all types), but for now, stick to comparing values of the same kind, which is what you'll do in almost every real program.

You
Memory-Leak Rat
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.