if, unless, and else
if, unless, and else are coding classics to create conditional branches which are used in most programming languages. These expressions evaluate to either true or false and execute the associated code blocks.
Two styles of syntax can be used for these expressions: multi-line and single-line.
Multi-line Syntax
For complex conditions or actions, or when including an else clause, the
multi-line syntax is most appropriate. It uses do…end to wrap the
executed code block.
# `if` expression
iex> num = 5
iex> if num > 3 do
...> IO.puts("#{num} is greater than 3")
...> end
# `unless` expression
iex> num = 2
iex> unless num > 3 do
...> IO.puts("#{num} is not greater than 3")
...> end
# `if` with `else` expression
iex> num = 2
iex> if num > 3 do
...> IO.puts("#{num} is greater than 3")
...> else
...> IO.puts("#{num} is not greater than 3")
...> end
Single-line Syntax
In a single-line syntax, the do: keyword follows the condition. This syntax is
often used for simple conditions and actions.
# `if` expression
iex> num = 5
iex> if num > 3, do: IO.puts("#{num} is greater than 3")
# `unless` expression
iex> num = 2
iex> unless num > 3, do: IO.puts("#{num} is not greater than 3")
Both styles are equally valid; the choice depends on the specific use case and code readability.
Remember, if, unless, and else are expressions, not statements. They always return a value, which can be
assigned to a variable or used in a larger expression.
|
if/2 is a Macro
In Elixir, if/2 is a macro, a special kind of function that is executed at
compile-time, before your program runs. It gets "translated" into a case/2
expression internally. This doesn’t have to bother you. I just felt that it was
good to know. In case you are more interested in this detail have a look at
Understanding if/2 Arity
In Elixir, when we say a function or macro has an arity of 2, we mean it accepts
two arguments. The if macro in Elixir has an arity of 2 because it requires
two arguments to work correctly: a condition and a keyword list.
You are now familiar with the if construct looking something like this:
if condition do
# Code executed when the condition is true
else
# Code executed when the condition is false
end
This is the most common way to use if in Elixir, and it’s very readable.
However, under the hood, Elixir is interpreting this in a slightly different way.
This 'do/else' style is actually syntactic sugar, a way to make the code look
nicer and easier to understand.
In reality, Elixir sees the if construct as follows:
if(condition, do: # Code to execute if true, else: # Code to execute if false)
Here, it’s clear to see that if is receiving two arguments:
-
The condition to evaluate, which should be either
trueorfalse. -
A keyword list that specifies what to
do:if the condition is true and what to doelse:if the condition is false.
So when we say if/2, we’re saying the if macro with two arguments: a condition
and a keyword list.