Sub topic 10
Iterating Values with for...of
This chapter assumes you already know the classic for loop and break/continue from earlier chapters. It also assumes you can read arrays, plain objects, arrow functions, and array destructuring such as const [a, b] = pair. The goal is to show you how for...of works internally, which values it accepts, and where it behaves differently than you might expect.
What for...of Does
for...of loops over the values produced by an iterable. An iterable is any object that knows how to hand out its values one at a time. You don't manage an index, a length check, or an increment. The loop asks the iterable for the next value until it reports that it is finished.
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
// red
// green
// blueCompare this with the counting loop it replaces:
const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}Both loops print the same thing. The for...of version has no off-by-one risk and no index variable to mistype. It also works on data structures that have no numeric index at all.
const is fine in the loop head
Each iteration gets a fresh binding, so const works here. In a classic for loop it would fail, because i++ reassigns the variable. Use const unless you plan to reassign the loop variable inside the body, which is rarely a good idea.
Built-in Iterables
Many built-in types are iterable, and each one decides for itself what "its values" are.
| Iterable | What each iteration yields |
|---|---|
| Array | Each element, in index order |
| String | Each Unicode code point (not each UTF-16 unit) |
| Map | A `[key, value]` pair |
| Set | Each value, in insertion order |
| `arguments` | Each argument passed to the function |
| DOM `NodeList` | Each node (in browsers) |
| Generator object | Each value it `yield`s |
Strings yield characters by code point
const word = "hi😀";
console.log(word.length); // 4 (the emoji is two UTF-16 units)
for (const ch of word) {
console.log(ch);
}
// h
// i
// 😀A classic for loop that indexes with word[i] would split the emoji into two broken halves. for...of keeps it whole, which makes it the safer choice when text can contain emoji or other characters outside the Basic Multilingual Plane. The two ways of counting can still disagree, though: word.length is 4 while the loop runs 3 times.
Maps and Sets
const stock = new Map([
["apples", 12],
["pears", 0],
]);
for (const [fruit, count] of stock) {
console.log(`${fruit}: ${count}`);
}
// apples: 12
// pears: 0
const tags = new Set(["js", "web", "js"]);
for (const tag of tags) {
console.log(tag);
}
// js
// webEach Map entry arrives as a two-element array, so destructuring in the loop head is the idiomatic way to name the parts.
Getting the Index Too
If you need the position as well as the value, use entries(). It yields [index, value] pairs:
const steps = ["install", "configure", "run"];
for (const [index, step] of steps.entries()) {
console.log(`${index + 1}. ${step}`);
}
// 1. install
// 2. configure
// 3. runMaps and Sets have keys(), values(), and entries() too. Arrays also have keys() if you only want indexes.
How It Works: The Iteration Protocol
for...of relies on two small agreements between objects, together called the iteration protocol.
- An object is iterable if it has a method under the key
Symbol.iteratorthat returns an iterator. - An iterator is an object with a
next()method. Each call returns{ value, done }. Whendoneistrue, iteration stops and thatvalueis ignored.
You can drive the protocol by hand to see what the loop does for you:
const letters = ["a", "b"];
const it = letters[Symbol.iterator]();
console.log(it.next()); // { value: 'a', done: false }
console.log(it.next()); // { value: 'b', done: false }
console.log(it.next()); // { value: undefined, done: true }Spread syntax ([...x]), array destructuring, Array.from, new Set(x), and Promise.all all use the same protocol. Once something works with for...of, it works with all of them.
Making Your Own Iterable
You can make any object iterable by giving it a Symbol.iterator method. Here is a version that implements the protocol by hand:
const range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true };
},
};
},
};
for (const n of range) {
console.log(n);
}
// 1
// 2
// 3
console.log([...range]); // [1, 2, 3]A generator function, written with function*, produces the same result with less code. Generators create iterators automatically:
const range = {
from: 1,
to: 3,
*[Symbol.iterator]() {
for (let i = this.from; i <= this.to; i++) {
yield i;
}
},
};
console.log([...range]); // [1, 2, 3]Because range creates a new iterator on every call to Symbol.iterator, you can loop over it as many times as you like.
Early Exit and Cleanup
When the body leaves the loop early through break, return, or a thrown error, for...of calls the iterator's optional return() method. For generators, that runs any finally block. This lets a data source release resources such as file handles or locks.
function* numbers() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log("cleanup");
}
}
for (const n of numbers()) {
if (n === 2) break;
console.log(n);
}
// 1
// cleanupGotchas
Plain objects are not iterable
This is the most common error with for...of:
const user = { name: "Ada", role: "admin" };
try {
for (const value of user) {
console.log(value);
}
} catch (err) {
console.log(err instanceof TypeError); // true ("user is not iterable")
}Plain objects have no Symbol.iterator. Turn the object into an array first with Object.keys, Object.values, or Object.entries:
const user = { name: "Ada", role: "admin" };
for (const [key, value] of Object.entries(user)) {
console.log(key, value);
}
// name Ada
// role adminThe next chapter covers for...in, which iterates object keys directly and comes with its own pitfalls.
Some iterators are single-use
Arrays hand out a fresh iterator every time you loop. A generator object is its own iterator, so after it runs once, it stays exhausted:
function* pair() {
yield "x";
yield "y";
}
const gen = pair();
console.log([...gen]); // ['x', 'y']
console.log([...gen]); // []If you need to loop twice, call the generator function again, or collect the values into an array first.
Mutating an array while iterating
The array iterator reads the current length on every next() call. Elements you push during the loop get visited, which can turn into an infinite loop:
const queue = [1, 2, 3];
for (const item of queue) {
if (item === 1) queue.push(4);
console.log(item);
}
// 1
// 2
// 3
// 4This is sometimes intentional, for example to process a work queue. When it isn't, loop over a copy: for (const item of [...queue]).
Holes in sparse arrays
for...of visits every index from 0 to length - 1, including holes, and yields undefined for each hole:
const sparse = [1, , 3];
for (const v of sparse) {
console.log(v);
}
// 1
// undefined
// 3Some array methods skip holes instead. Keep this difference in mind if your arrays come from code that leaves gaps.
Exercises
Exercise
What does this code print, and why? const s = "a😀b"; let count = 0; for (const c of s) count++; console.log(count, s.length);
Show answer
It prints "3 4". for...of iterates by Unicode code point, so the emoji counts as one character. The length property counts UTF-16 code units, and the emoji takes two.
Exercise
A teammate writes for (const v of settings) where settings is a plain object, and gets "TypeError: settings is not iterable". Give two ways to fix it, one for values only and one for key-value pairs.
Show answer
Plain objects have no Symbol.iterator method. For values only, use for (const v of Object.values(settings)). For key-value pairs, use for (const [key, value] of Object.entries(settings)).
Exercise
Write an object countdown with a start property set to 3, so that [...countdown] returns [3, 2, 1] and spreading it a second time returns the same result.
Show answer
const countdown = { start: 3, *[Symbol.iterator]() { for (let i = this.start; i > 0; i--) yield i; } }; Each spread calls the generator method again, which creates a fresh iterator, so the object can be iterated any number of times.
Exercise
In the numbers() generator example, what would print if the loop body used continue instead of break when n === 2?
Show answer
It would print 1, 3, then "cleanup". continue moves on to the next value without leaving the loop, so the generator runs to the end, and its finally block runs when it finishes normally.