All lessons

Loops

7 min · Elixir

Repeat work by walking over a range.

Elixir · Loops0/5 cleared

Enemy 1 of 5

Enum.each and ranges

If you've used other languages, you might expect a `for (i = 0; i < 3; i++)`-style counter loop here — Elixir deliberately doesn't have one. Because Elixir data is immutable, there's no variable to keep incrementing in place the way a classic counter loop relies on. Instead, repetition happens by walking over an existing collection (a list, a range, a map) and running a function once per element — the walking and bookkeeping is handled for you by functions in the `Enum` module.

This is a real shift in how you think about repetition: instead of "start a counter, check a condition, increment, repeat," you think in terms of "here is a collection of values, run this action for each one." It reads more like a description of *what* should happen than a mechanical recipe for *how* to loop.

`Enum.each(collection, fn)` calls the given function once for every element of `collection`, in order, and is used purely for its side effects (like printing) — it doesn't build up a new collection the way `Enum.map` will later. The function itself is written as `fn i -> ... end`, an anonymous function taking one parameter `i`.

A range like `0..2` represents every integer from 0 to 2 inclusive — unlike some other range syntaxes you might meet later, Elixir's `..` range includes both endpoints, so `0..2` covers exactly 0, 1, and 2, three values total.

You
Invisible Heisenbug

Loading editor...

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