Making Decisions
7 min · Elixir
Run different code depending on whether something is true.
Enemy 1 of 5
if / else syntax
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.
Loading editor...