All lessons

Variables

6 min · Elixir

Store values in named boxes called variables.

Elixir · Variables0/5 cleared

Enemy 1 of 5

Binding a value and printing it

In Elixir, `name = value` is usually called "binding" a value to a name rather than "assigning" it, and the distinction is more than just vocabulary. Elixir's data itself is immutable — once a piece of data (a number, a string, a list) is created, it can never be changed in place. What `=` does is attach a name to a value so you can refer to it later; if you write `name = "Ada"` and then later `name = "Grace"`, you haven't mutated anything — you've simply rebound the name `name` to point at a different, brand-new value. The original `"Ada"` string still exists unchanged, it's just no longer referred to by that name.

This immutability-by-default is one of the biggest mental shifts coming from languages like Python or JavaScript, where variables are commonly mutated in place. In Elixir, functions never sneakily change data you hand them — they only ever return new data — which makes it much easier to reason about what a piece of code could possibly have done to your values.

The syntax itself is simple: `name = value` binds, and the name can be used anywhere afterward as if it were the value itself. `IO.puts(name)` prints whatever `name` is currently bound to.

Elixir infers the type of every value automatically — there's no type to declare when binding. `name = "Ada"` is a string, `age = 36` is an integer, and Elixir figures that out from the literal itself, the same way it will for every value you bind from here on.

You
Cold-Start Frostling

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Ada