Making the connection between JS for loops and Elixir for loops

Joel Kemp
Joel Kemp
Sep 14, 2020 · 1 min read

When writing some Elixir code, I come across wanting to express something in a for loop. Of course there are constructs like each, map, reduce, and such in Elixir (and JavaScript), but I wanted to see to achieve the classic for loop in Elixir.

I only use JavaScript here since that was the language I used and studied extensively before diving deep into Elixir.

In JavaScript, the classic for loop looks like:

// JavaScript
for (var i = 0; i < a.size; i++) {
console.log(a[i])
}

In Elixir, using comprehensions and ranges, that would translate to:

// Elixir
for i <- 0..Enum.count(a) - 1 do
IO.puts(Enum.at(a, i))
end

If you wanted to unnest operations in the Elixir case, you could expand that to:

// Elixir (without nesting)
for i <- 0..Enum.count(a) - 1 do
a
|> Enum.at(i)
|> IO.puts()
end

I’m sure there are other ways to express this in Elixir as well, but I’ll get there eventually. Cheers!

Elixir Learnings

Quick articles on tips/tricks/learnings with the Elixir programming language