Try Install Learn Blog API Packages GitHub


for...of is useful for iterating over either an Array(a) or a Set(a) or a Map(a,b)

The result of the iteration is always an array where the type of its items is from the type of the expression.

In the next example we iterate over an array of Strings and making them uppercase:

for (item of ["bob", "joe"]) {
/* The result will be ["BOB", "JOE"] */

or in this example you can iterate over a map:

map =
  |> Map.set("name", "bob")
  |> Map.set("age", "33")

for (key, value of map) {
  String.toUpperCase("#{key}: #{value}")
/* The result will be ["name: bob", "age: 33"] */

The return type of this for...of expression is Array(String).

Selecting items

You can limit the items for which the iteration should take place with an optional when block:

for (item of ["bob", "joe"]) {
} when {
  item == "bob"
/* The result will be ["BOB"] */

In the example we specified that the expression should only run (and return) for items which equals "bob".