The for...of loop
Learn to iterate over array values with for...of.
Looping over values with for...of
The for...of loop iterates over the values of an array. Unlike the classic for loop, it needs no index or counter.
Syntax: for (const element of array) { ... }. On each iteration element takes the next value.
Example: for (const color of colors) { console.log(color); } prints each color.
for...of versus forEach
for...of is a statement; you can exit early with break or skip with continue.
forEach is a method; it cannot be stopped with break. When you need early exit, choose for...of.
For the index, use forEach's second parameter or a classic for loop; for...of does not give the index directly.
Exercise Print the letters array with for...of
Create an array named letters with at least four letter strings. Use for...of to print each letter with console.log.
Show example solution
Write the array with square brackets, then traverse with for...of.
Example solution:
const letters = ["a", "b", "c", "d"];
for (const letter of letters) {
console.log(letter);
}
Test yourself
-
Print colors with for...of
const colors = ["red", "blue", "green"]; for (const color of ____) { console.log(color); }Show answer
const colors = ["red", "blue", "green"]; for (const color of colors) { console.log(color); } -
What is n on the first iteration?
const nums = [10, 20, 30]; for (const n of nums) { console.log(n); }- 10
- 0
- 1
- nums
Show answer
10 — Correct. for...of gives the first value on the first iteration; here 10.
-
Match each loop type with its behavior
- for...of
- gives values
- forEach
- runs a callback
- for (classic)
- gives the index