🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Variables

A variable is a name that holds a value. Programs use the name to work with the value later.

A name holds a value

The first line binds the text Ana to the name name. The second line prints the value the name holds.

name = "Ana"
IO.puts(name)

A name can be rebound

The name city first holds Paris. A second = line rebinds it to London, and the prints show both values in order.

city = "Paris"
IO.puts(city)
city = "London"
IO.puts(city)

Each name holds its own value

Two names hold two different values here. Each print reads the value of its own name.

player = "Bo"
score = 30
IO.puts(player)
IO.puts(score)

Example

name = "Ana"
city = "Paris"
IO.puts(city)
city = "London"
IO.puts(name)
IO.puts(city)

Key points

  • Variable: a name that holds a value.
  • Binding: the equals sign in name = value connects the name to a value.
  • Use the name on its own to read the value it holds.
  • Rebinding: giving the same name a new value with another = line.
  • Names: variable names start with a lowercase letter, such as name or score.

In this example, the first line binds Ana to the name name. The second line binds Paris to city, and the next print shows Paris. City is then rebound to London, and the last two prints show Ana and London.

Note

a variable in Elixir is rebound to a new value rather than changed in place.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

After the lines x = 1 and then x = 2, what does IO.puts(x) print?