Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 48 ยท Core Language

Immutability and Rebinding

Understand why Elixir data never changes in place, how rebinding differs from mutation, and how structural sharing keeps new copies cheap.

In many languages you change a value in place: you push onto an array, assign to a field, or increment a counter. Elixir works differently. Every value is immutable: once it exists, nothing can modify it. When you "change" a list or a map, you really build a new value and, if you want, point a name at it.

This sounds like a restriction, and it is a deliberate one. When data cannot change behind your back, you can pass it to any function, or any other process, without worrying that someone will alter it. That one rule is a big reason Elixir programs are easy to reason about and safe to run concurrently. It builds on what you saw in Pattern Matching: The = Operator.

Values never change

Immutable A list or map is fixed once created.
Names move A variable can point at a new value.
New copies Functions return new data.

Changing data means building new data.

1 / 2

Values versus names

In Elixir a variable is just a name bound to a value. Binding is not a box that holds changing contents. Look at this read-only example:

ELIXIR
x = 1
y = x
x = 2

IO.puts(x)   # 2
IO.puts(y)   # 1

The line x = 2 did not alter the number 1. It made the name x refer to a different value. y still refers to 1, because the value it received was never touched. This is called rebinding, and it is the only "change" a variable ever goes through.

Rebinding is allowed, but only in the scope where it happens. A rebinding inside a function body, if, case or for does not leak out:

ELIXIR
count = 10

if true do
  count = 99
  IO.puts(count)  # 99
end

IO.puts(count)    # 10, the outer name is unchanged

If you want a value computed inside a branch, return it from the branch and bind it outside:

ELIXIR
count =
  if true do
    99
  else
    10
  end

Rebinding is convenient in pipelines of small steps (line = String.trim(line)), but reusing one name for many unrelated things makes code hard to read. Give each step a clear name when the meaning changes.

Functions return new data

Functions in the standard library never modify their arguments. They return a new value:

ELIXIR
numbers = [3, 1, 2]
sorted = Enum.sort(numbers)

IO.inspect(numbers)  # [3, 1, 2]
IO.inspect(sorted)   # [1, 2, 3]

numbers is exactly what it was before. This is true for every data type: strings, tuples, lists, maps and structs. A function like Map.put/3 or List.delete/2 hands back the updated version and leaves the original alone. A common beginner mistake is to call such a function and ignore the result. The compiler may warn you, because nothing happened to the original:

ELIXIR
user = %{name: "Ana"}
Map.put(user, :age, 30)   # result thrown away
IO.inspect(user)          # %{name: "Ana"}, still no age

The fix is to bind the result: user = Map.put(user, :age, 30).

Closures capture values

Because values cannot change, an anonymous function that captures a variable captures its value at that moment. Rebinding the name later has no effect on the function:

ELIXIR
rate = 2
double = fn n -> n * rate end

rate = 10
IO.puts(double.(5))  # 10, uses the value 2 that was captured

This surprises programmers coming from languages where closures see later assignments. In Elixir the behavior is simple and predictable: the closure holds the number 2.

Structural sharing

If every update builds a new value, is Elixir wasteful with memory? Not usually. Immutable data lets the runtime share the parts that did not change. Take a linked list (more in Tuples and Lists):

ELIXIR
tail = [2, 3, 4]
a = [1 | tail]
b = [0 | tail]

Both a and b are new lists, but neither copies tail. They each hold one new cell that points at the same existing cells. Prepending is therefore cheap and takes constant time. Maps and other structures use similar tricks: updating one key of a large map creates a small amount of new structure and reuses the rest.

Since sharing is invisible (no one can mutate the shared part), it is always safe. It also explains a performance rule you will meet later: putting an element at the front of a list is cheap, while appending at the end must rebuild every cell.

A JavaScript stand-in

Elixir itself does not run on this site, so the editors below use JavaScript to imitate the idea. Frozen objects cannot be modified, so "updates" create new objects. This is a stand-in written to show the concept. Real Elixir enforces immutability for everything automatically, and its runtime has its own representation of data.

JS Update without mutating (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The original object survived every operation. Only the name older points at the new object, which is the same idea as rebinding in Elixir.

The next stand-in shows sharing. Both new lists point at the same tail object, and a strict identity check proves it.

JS Sharing a tail (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After x = 1, y = x and x = 2, what is y?

    Rebinding x points the name at a new value. y still refers to the value 1 it received earlier.
  2. 2. What does Map.put(user, :age, 30) do to user if you do not bind the result?

    Values are immutable, so Map.put returns a new map. Without binding it, the original stays unchanged.
  3. 3. Why is [0 | tail] cheap?

    Structural sharing: only one new cell is created and it points at the existing tail, which is safe because nobody can change it.
  4. 4. In rate = 2; f = fn n -> n * rate end; rate = 10, what does f.(5) return?

    The closure captured the value 2 when it was created. Rebinding the name later does not affect it, so the result is 10.

Summary

  • Elixir values are immutable; functions return new values instead of editing old ones.
  • A variable is a name for a value, and rebinding moves the name, not the data.
  • Rebinding inside if, case or a function does not leak into the outer scope.
  • Closures capture the value a name had when the function was created.
  • Structural sharing keeps new versions cheap, especially when you prepend to a list.
  • Always bind the result of an "update" function, or the change is lost.

Next up: Operators and Comparison.