Skip to content
Theory · Conditions and loops · lesson 7 of 13

The for…of loop

Picture a shopping list: milk, bread, apples. In the store, you go down it from top to bottom and pick up each item in turn. You don't need the item's number; the item itself is what matters. When the items run out, the shopping is done.

A counter loop goes through numbers. To go through values, such as the letters of a word or the items of a list, there is the for…of loop. It takes the values in order and stops when they run out, so it needs neither a counter nor a condition:

JavaScript
const colors = ["red", "green", "blue"];

for (const color of colors) {
    console.log(color);
}
// red
// green
// blue

The array

Values in square brackets separated by commas form an array, an ordered list. Each value in it is called an element, and the element's number is called its index. The array colors has three elements.

Indexes start at 0: "red" has the index 0, "green" has 1, and "blue" has 2. Here the shopping list and the array part ways: the items of a list are usually numbered from one, while the elements of an array are numbered from zero.

The for…of loop

for…of goes through both arrays and strings. Let's look at each case.

Over an array

Let's walk through the first program:

  1. const colors = ["red", "green", "blue"] creates an array of three elements.
  2. On the first iteration, color gets "red", and the body prints red.
  3. On the next iterations, color gets "green", then "blue".
  4. The elements run out, and the loop stops by itself.

Over an empty array [], the loop body never runs.

On every iteration, for…of creates a new variable and puts the next element into it. The variable does not change within the iteration, so it is declared with const. A counter loop cannot do that: the step i++ changes the variable, so it needs let.

Over a string

Over a string, for…of goes character by character. This program counts the letters a in a word:

JavaScript
let count = 0;

for (const ch of "banana") {
    if (ch === "a") {
        count++;
    }
}

console.log(count); // 3

The variable ch takes the values "b", "a", "n" and so on in turn. On every letter a, the condition is true, and the counter grows by one.

break and continue work inside for…of as they do in a counter loop.

Sum of the elements

The most common job for for…of is to build one result from the elements. Back to the store: at the checkout, you add up the prices of all the items one by one. The program does the same:

JavaScript
const prices = [120, 45, 300];
let total = 0;

for (const price of prices) {
    total += price;
}

console.log(total); // 465

Let's go step by step:

  1. Before the loop, total is 0: nothing in the basket has been counted yet.
  2. On the first iteration, price gets 120, and total becomes 120.
  3. Then price gets 45, and total becomes 165.
  4. On the last iteration, price is 300, and total becomes 465.

The variable total is declared with let and before the loop. Declared in the loop body, it would be created again with zero on every iteration, and it would not be visible after the loop.

Common mistake

The loop variable is given a new value to change an element of the array:

JavaScript
const prices = [120, 45, 300];

for (let price of prices) {
    price = price * 2; // ✗
}

console.log(prices); // [ 120, 45, 300 ]

There is no error, but the array stays the same. The loop puts a copy of the number into price, and the assignment changes only that copy. On the shopping list, it is like a price rewritten on a separate slip: the price tag in the store does not change.

If you need a new result, build it in a separate variable, like total above.

Key points

  • An array is an ordered list of elements, and the indexes of its elements start at 0.
  • for…of goes through values: the elements of an array or the characters of a string.
  • The loop variable is declared with const: it is a new one on every iteration.
  • A new value of the loop variable does not change the array; the result is built in a separate variable.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way