Table of Contents
- Binding - Creating Variables
- Naming Variables
- Rebinding - Updating Variable Values
- Memory Management in Elixir
- References
Binding - Creating Variables
In Elixir, we can give a name to a value just like in most programming languages. The syntax may look familiar, but under the surface, the idea of a “variable” works quite differently from how it does in languages like Python or JavaScript.
First, let’s take a quick look at how variable assignment works in an imperative language like Python.
In Imperative Languages: A Refillable Box
Here is a typical Python example:
>>> monthly_salary = 1000
>>> monthly_salary = 1500
You can imagine monthly_salary
as a box with a label. First, the box holds 1000
. Then, we open the box and replace its contents with 1500
.
The box itself stays the same, but the value inside it changes. This is called mutability, which means a value can be updated after it has been created. This is common in imperative languages, where programs are written as a series of steps that change the state of the system over time.
In Elixir: A Sealed Box
Now let’s see how Elixir handles the same idea:
iex> monthly_salary = 1000
This might look like the Python example at first glance, but under the hood, it behaves very differently.
Let’s use the box analogy again. In Elixir, we are creating the value 1000
, putting it into a box, sealing the box shut, and attaching the label monthly_salary
to it. Once the box is sealed, its contents cannot be changed.
This concept is called immutability. A value, once created, cannot be modified.
Here are a few simple expressions:
iex> monthly_salary = 1000
1000
iex> monthly_salary
1000
iex> monthly_salary * 12
12000
So far, everything is working as expected. But what if we try to “change” the value?
iex> monthly_salary = 1500
At first glance, this looks like we’re changing the value of monthly_salary
. But actually, we are not.
We are not opening the original sealed box and changing what's inside. Instead, Elixir creates a new sealed box containing 1500
. Then, it detaches the label monthly_salary
from the old box and attaches it to the new one.
The label stays the same, but it now points to a different box. The old box still exists, but since it no longer has a label attached to it, it's considered unused.
This is a fundamental idea in functional programming: values never change. If we need a different value, we create a new one and rebind the name.
When an old value is no longer referenced by any name, Elixir will automatically clean it up. We will talk more about that in the memory management section.
Type Inference
Since Elixir is a dynamically typed language, it figures out the type of a value automatically based on what we assign to it. We do not need to specify the type manually:
name = "Alice" # string
age = 30 # integer
height = 1.72 # float
Even though we don't write the types, Elixir keeps track of them internally and uses them correctly at runtime.
Naming Variables
In Elixir, variable names must start with a lowercase letter (a
to z
) or an underscore (_
). After the first character, the name can contain letters, digits (0
to 9
), or additional underscores. Underscores are commonly used to separate words for readability.
# Valid variable names:
valid_variable_name
also_valid_1
validButNotRecommended
Variable names that start with uppercase letters are not allowed:
# Invalid:
VariableName # error: capital letter at the beginning
Trailing Question Mark and Exclamation Mark
Elixir allows variable names to end with a question mark (?
) or an exclamation mark (!
). These characters do not affect how the code runs. They are just conventions that give extra meaning to the name.
A question mark usually means the variable holds a boolean value or the result of a logical check. FOr examples: valid?
, empty?
, active?
An exclamation mark often means the value is guaranteed to exist, or that it came from a function that may raise an error if something goes wrong. For example, we might name a variable data!
to show that it comes from File.read!/1
, which will crash if the file cannot be read:
user_valid? = true
processed_data! = File.read!("config.exs")
We are not required to use these suffixes, but following these conventions makes our code easier to understand. This is especially helpful when working on large projects or with a team.
Rebinding - Updating Variable Values
As we have seen, Elixir values are immutable. This means we cannot change them once they are created. But we can rebind the same name to a new value.
iex> monthly_salary = 1000
iex> monthly_salary = 1500
We are not modifying the existing value. We are creating a new one, and then binding the name monthly_salary
to this new value.
Rebinding simply updates the association between the name and a different value. The original value still exists in memory, but it is no longer connected to that name.
Here’s a full example:
iex> monthly_salary = 1000 ❶
1000
iex> monthly_salary ❷
1000
iex> monthly_salary = 1234 ❸
1234
iex> monthly_salary ❹
1234
Explanation:
- ❶ The name
monthly_salary
is first bound to1000
. - ❷ When we check its value, it still points to
1000
. - ❸ We rebind the same name to
1234
. - ❹ Now,
monthly_salary
refers to the new value.
The old value (1000
) is no longer in use. Elixir will eventually remove it from memory when it is no longer needed.
Memory Management in Elixir
Elixir includes a garbage collector (GC), which is part of the runtime system. Its job is to find data that is no longer being used and free the memory it occupies.
Let’s take another look at rebinding:
iex> monthly_salary = 1234
iex> monthly_salary = 2000
After the second line, the name monthly_salary
now refers to 2000
. The earlier value 1234
is no longer referenced by any name. At this point, Elixir considers it unused and will automatically clean it up.
This entire process happens behind the scenes. You do not need to manually allocate or release memory. The runtime handles it for you, so you can focus on writing the logic of your program without worrying about memory leaks.
References
- Saša Jurić. (2024). Elixir In Action (3rd ed.). Manning Publications.
Top comments (0)