Visiting Each Item

Many loops do not care about positions. They just want to visit each item, one after another. for...of does exactly that:

for (const letter of "abc") {
  console.log(letter);
}

Output:

a
b
c

You can read it as "for each letter of the string". On each pass, the loop variable letter holds the next item. There is no counter to set up, and no < or <= to get wrong. for...of works on strings, and on lists of values (called arrays), which you will learn in the Arrays section. When you do not need positions, use for...of.

You may be surprised to see const here, because the loop runs many times. But each pass gets a new letter variable. Inside one pass, nothing changes it, so const is correct. It also stops you from changing the item by mistake.

This loop is useful for input. Often one line of input holds several values, like 4 8 15. In the reading-input lesson, .split("\n") cut the input into lines. .split(" ") cuts a line into pieces at each space, and for...of can visit the pieces:

const parts = "4 8 15".split(" ");
let total = 0;
for (const part of parts) {
  total += Number(part);
}
console.log(total);

Output:

27

Each piece is still a string, like "4", so you convert it with Number() before adding. Use this split, loop and convert pattern whenever you need to read a line of numbers.

Look at total too. It starts at 0 before the loop, and each pass adds one number to it. A variable that collects a result like this is called an accumulator. You will use the same idea for sums, counts and much more.

In the exercise, read a line of numbers, print each number doubled, and then print the total.