JavaScript For Of
The for...of loop walks the values of a list one by one. The loop variable holds each value in turn.
Values from an array
Each turn hands over one fruit name. No index appears anywhere in the loop.
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}Letters of a string
A string is a list of characters. The loop hands over one letter at a time.
const word = "cat";
for (const letter of word) {
console.log(letter);
}Values from a set
A set holds each value once. The repeated red was dropped when the set was built.
const colors = new Set(["red", "blue", "red"]);
for (const color of colors) {
console.log(color);
}Example
const prices = [4, 8, 15];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(total);Key points
- The loop variable holds the value itself, not an index.
- for...of works on arrays, strings, and sets.
- Use const for the loop variable when the loop does not change it.
- An index loop reads items by position. for...of reads items by value.
In this example, the loop visits each price in the array. Each price is added to the running total. The log after the loop shows the finished sum, 27.
Note
for...of gives no index. Use an index loop when the position matters.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does the loop variable hold in a for...of loop?