liveBook · Manning

Unless expression

As explained in Elixir in Action, Third Edition

An unless expression conditionally evaluates one branch when its condition is false and another branch otherwise.

An unless expression selects a branch based on a false condition. It is equivalent to an if expression with the condition negated: the main branch runs unless the condition is truthy, while the else branch runs otherwise. section 3.3.2 section 2.6

Guarding a notification

Use unless when the exceptional condition reads more clearly as the condition to avoid: unless result == :error, do: send_notification(...). The equivalent conventional form is if result != :error, do: send_notification(...). section 3.3.2

unless some_expression do
 block_1
else
 block_2
end

The block form supports separate main and else branches; conceptually, it transforms into an if expression with the branches reversed. section 2.6

How Elixir in Action, Third Edition covers it

How deep it goes
Defines branch behavior and shows its macro-level transformation into if, without detailed macro implementation.
Examples
Uses notification sending to contrast an unless guard against its equivalent positive if condition.
What you can do after
Apply it via Elixir syntax to express negative conditions with block or one-line branches.
How it connects
Connects conditional branching with if expressions, macros, compile-time transformation, and Elixir's small language core.

Also explained in

Compare how 2 books explain unless expression →

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.