Coding for All
Lesson 17: for...of Loops
for...of Loops Visit every item in an array, one by one.
1const fruits = ["apple", "banana", "cherry"];
2for (const fruit of fruits) {
3 console.log(fruit);
4}
Terminal
$ node main.js
apple
banana
cherry
Every line, explained
const fruits = ["apple", "banana", "cherry"];
An array stores several values in one variable. The values go between square brackets, separated by commas.
for (const fruit of fruits) {
for...of visits each item in the array, one trip around the loop per item. Each time, the loop variable holds the current item, and since we never reassign it ourselves, it is declared with const. This is the modern JavaScript way to loop over an array. Naming the loop variable fruit (singular) and the array fruits (plural) makes it read like English: "for each fruit of fruits".
console.log(fruit);
console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. Runs three times, once per item, and fruit is different each time.
}
This } closes the for loop.