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:
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
// red
// green
// blueThe 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:
const colors = ["red", "green", "blue"]creates an array of three elements.- On the first iteration,
colorgets"red", and the body printsred. - On the next iterations,
colorgets"green", then"blue". - 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:
let count = 0;
for (const ch of "banana") {
if (ch === "a") {
count++;
}
}
console.log(count); // 3The 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:
const prices = [120, 45, 300];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(total); // 465Let's go step by step:
- Before the loop,
totalis0: nothing in the basket has been counted yet. - On the first iteration,
pricegets120, andtotalbecomes120. - Then
pricegets45, andtotalbecomes165. - On the last iteration,
priceis300, andtotalbecomes465.
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:
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…ofgoes 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.