liveBook · Manning

Conditional logic

As explained in Elixir in Action, Third Edition

A conditional expression evaluates one of multiple branches according to a condition or a matched pattern.

Elixir treats branching as expression-oriented control flow. Classical conditionals remain useful when creating multiclause functions would add unnecessary structure. section 3.0 section 3.3.2

Choose the branching form that matches the decision:

  • Use if or unless for a single truthiness test; the selected block’s last expression becomes the return value, and if without else returns nil when false. section 3.3.2
  • Use cond for multiple boolean conditions, ordering clauses from most specific to fallback; unmatched conditions raise an error. section 3.3.2
  • Use case when branching by patterns, while multiclause functions can replace many conditional forms. section 3.0 section 3.3.2

Status classification

A call-status function can check populated fields in order: return :ended when ended_at exists, :started when started_at exists, and :pending through a final true clause. section 3.3.2

if condition do
 ...
else
 ...
end

Use the compact listing to compare Elixir’s multiline if form with its expression-oriented branching syntax. section 3.3.2

How Elixir in Action, Third Edition covers it

How deep it goes
Explains if, unless, and cond behavior, return values, fallbacks, and errors, while connecting case to pattern matching.
Examples
Uses max calculations, notification guards, and call-status classification to demonstrate branching choices.
What it assumes
Assumes Elixir’s basic building blocks and foregrounds pattern matching before branching.
What you can do after
Apply it via Elixir’s if, unless, cond, case, and multiclause-function forms.
How it connects
Connects conditional logic with pattern matching, multiclause functions, and expression-oriented programming.

Also explained in

Compare how 21 books explain conditional logic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.