Executing Code and Generating a Result

Learn about executing code in Elixir to generate a result.

Generating results for expressions

Elixir can generate a result for any expression. The process is similar to solving mathematical equations: to generate a result, we must add or multiply some numbers or change some Xs to Ys. We’ll create expressions for the computer, and the computer will show us the result. The simplest expression is a value, like this:

iex> 42
#Output -> 42

IEx shell is present at the end of the lesson to try out the different examples.

The number 42 is an expression that evaluates to the value we typed. Let’s try a different expression:

iex> 1 + 1
#Output -> 2

The number 1 is a value, and + is an operator. Operators compute values and generate a result.

Operator precedence

We can also combine multiple operators and values:

iex> (2 + 2) * 3 
#Output -> 12

iex> 2 + 2 * 3
#Output -> 8

Each operator is executed in a particular order, which is called its precedence. For example, * has higher precedence than +. In an expression that has both operators, the * operator will be executed first. we can use parentheses to change the precedence. Expressions within parentheses are computed first.

We can always check the operator’s precedence in the Elixir official documentation.

Get hands-on with 1400+ tech skills courses.