Sub topic 13
Under the Hood: Symbol.iterator and next()
This chapter assumes you know how for...of works on arrays, strings and Maps, and that you can read basic object and function syntax. Here you will see what for...of does each time it runs.
Two Protocols, Two Roles
for...of depends on two small agreements called protocols.
- An iterable is any object with a method stored under the key
Symbol.iterator. When you call that method, it returns an iterator. - An iterator is an object with a
next()method. Each call returns a result object of the form{ value, done }.
When done is false, value holds the next item. When done is true, the sequence has ended, and value is usually undefined.
const iterator = ['a', 'b'][Symbol.iterator]();
console.log(iterator.next()); // { value: 'a', done: false }
console.log(iterator.next()); // { value: 'b', done: false }
console.log(iterator.next()); // { value: undefined, done: true }What for...of Actually Does
A for...of loop works roughly like this manual version:
const letters = ['x', 'y', 'z'];
const it = letters[Symbol.iterator]();
let result = it.next();
while (!result.done) {
const letter = result.value;
console.log(letter);
result = it.next();
}
// x
// y
// zThe loop asks the iterable for one fresh iterator, then calls next() until done is true. The value that comes with the final done: true result is not passed to the loop body.
Checking Whether Something Is Iterable
A plain object has no Symbol.iterator method, so for...of throws a TypeError on it. You can test for the method directly:
const isIterable = x =>
x != null && typeof x[Symbol.iterator] === 'function';
console.log(isIterable([1, 2])); // true
console.log(isIterable('hi')); // true
console.log(isIterable(new Set())); // true
console.log(isIterable({ a: 1 })); // falseIterators Get Used Up
Built-in iterators are iterable too. Their Symbol.iterator method returns the iterator itself. That means you can pass an iterator to for...of or to spread syntax, but it remembers its position and only runs once.
const it = [1, 2, 3][Symbol.iterator]();
console.log([...it]); // [1, 2, 3]
console.log([...it]); // []An array, by contrast, hands out a new iterator on every call. That is why you can loop over the same array as many times as you like.
| Object | Has `Symbol.iterator` | Has `next()` | Reusable |
|---|---|---|---|
| Array, String, Map, Set | Yes | No | Yes, a fresh iterator each time |
| Array iterator (`arr.values()`) | Yes, it returns itself | Yes | No, it is used up after one pass |
| Plain object | No | No | Not iterable |
Exercise
Given const m = new Map([['a', 1]]); const it = m.entries();, what do the first two calls to it.next() return?
Show answer
The first call returns { value: ['a', 1], done: false }. The second returns { value: undefined, done: true }, because the Map holds only one entry.
Exercise
Why does for (const v of { a: 1 }) {} throw, while for (const v of Object.values({ a: 1 })) {} works?
Show answer
The plain object has no Symbol.iterator method, so it is not iterable. Object.values returns an array, and arrays implement Symbol.iterator.