for...of
- Node.js course
- Beginner
- Lesson 44/116
- 4 min
Learn to iterate over iterables with for...of.
The for...of loop
To walk the elements of an array (or any other iterable) in order you use for...of. The form is for (const item of items) { ... }. On each iteration item takes the next element.
For example const fruits = ["apple", "pear", "banana"]; for (const f of fruits) { console.log(f); } prints the three fruits one per line. for...of works with elements directly, not indices; when no index is needed it reads better than for (let i = 0; ...). A string is also iterable; you can walk each letter.
The iterable concept
An iterable is a data structure whose elements can be walked one by one. In JavaScript arrays, strings, Map, Set and NodeList are iterables. for...of works only on iterables.
Plain objects are not iterable; walking them with for...of throws. To walk object keys use for...in or Object.keys(). The iterable concept clarifies which data types a loop can work on; later, iterators and generators build on this foundation.
Practice Print the fruits
The fruits variable holds ["Apple", "Pear", "Banana"]. Write a for...of loop: walk each fruit with const f of fruits and print it with console.log(f). The output must be three lines: Apple, Pear, Banana.
Starter code
const fruits = ["Apple", "Pear", "Banana"];
// Write the for...of loop hereSample solution
const fruits = ["Apple", "Pear", "Banana"];
for (const f of fruits) {
console.log(f);
}Expected output
Apple Pear Banana
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the for...of header
const fruits = ["apple", "pear"];
____ (const f of fruits) {
console.log(f);
}
const fruits = ["apple", "pear"];
for (const f of fruits) {
console.log(f);
}
Explanation: for...of walks the elements.
2 Match each data type to its case
| Term | Meaning |
|---|---|
Array |
for...of for elements |
String |
for...of for letters |
Object |
for...in for keys |
Map |
for...of for pairs |
3 What is the output of for (const x of [10, 20, 30]) { console.log(x); }?
for (const x of [10, 20, 30]) { console.log(x); }- 0 1 2
- 30 20 10
- 10
- 10 20 30 Correct answer
Explanation: for...of gives elements in order; 10, 20, 30 are printed.