Loops
for...of loop
A loop that hands you each value of an array, string or Set in turn.
Why it exists
Most loops need the item itself, not its position: add up prices, check each user, show each message. The classic for makes you write bookkeeping code (let i = 0; i < arr.length; i++ and arr[i]) where off-by-one mistakes hide. for...of removes the noise and reads like a sentence: "for each value in the collection, do this".
Where it's used
- Go through the items in a cart and add up the total.
- Check every field of a form and collect the errors.
- Go through the characters of a string — for example, to count vowels.
- Search for something and stop at the first match with return or
break.
Syntax
for (const item of collection) {
// ...
}Examples
const prices = [120, 80, 45];
let total = 0;
for (const price of prices) {
total += price;
}
total; // → 245let vowels = 0;
for (const ch of "programming") {
if ("aeiou".includes(ch)) vowels++;
}
vowels; // → 3function firstNegative(numbers) {
for (const n of numbers) {
if (n < 0) return n;
}
return null;
}
firstNegative([4, -2, -7]); // → -2return stops both the loop and the function at the first matchResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
for...of works with any iterable value — anything that can hand out items one at a time: arrays, strings, Set, Map. On every step the loop asks the collection for the next value and puts it into the variable.
The variable is created anew on every step, so you can declare it with const: it doesn't change within one step.
Unlike forEach, this is a real loop, not a function call. So return inside it ends the whole surrounding function, and break stops the loop. In forEach, return would only end the current step, and there'd be no way to stop early.
Traps
How it differs from…
When to pick something else
Practice
- Cart total
- Average rating
- Largest number
- Count occurrences
- How many vowels
- No duplicates
- Any duplicates?
- Check a sudoku row
- Order total
- Only the fields you need
- Letter frequency
- Invert an object
- Group by a property
- One shared list
- Brackets in order
- Roman numerals
- Comment counter
- Cats looking for a home
- Tabs
- Resolve the conflict
Lessons where this appears
- The sock warehouseWorkshop · Chapter 5 · Arrays and loops
- Largest numberLab · Chapter 5 · Arrays and loops
- Invert an objectLab · Chapter 9 · Destructuring, spread and rest
- Has duplicatesLab · Chapter 11 · Map and Set
- Comment counterLab · Chapter 13 · Recursion
- Order totalLab · Chapter 17 · Project: an online shop