Custom Iterators and for...of Loops
for...of works on any object that has a Symbol.iterator method. Plain objects do not have one, but you can add it yourself, and then you decide which values the loop sees and in what order. The method must return an iterator, which is an object whose next() method returns { value, done } each time it is called.
Use a custom iterator when an object holds a collection, such as a playlist, a shopping basket or a range of numbers, and the code that uses it should not need to know how the collection is stored.
Adding Symbol.iterator to an object
Section titled “Adding Symbol.iterator to an object”This object holds a list of tracks, and its iterator yields the tracks in order. The method is written with a computed property name, [Symbol.iterator], because a symbol cannot be written as a plain key:
const playlist = { name: 'Morning run', tracks: ['Intro', 'Uphill', 'Cool down'], [Symbol.iterator]() { let index = 0; const tracks = this.tracks; return { next() { if (index < tracks.length) { return { value: tracks[index++], done: false }; } return { value: undefined, done: true }; }, }; },};
for (const track of playlist) { console.log(track);}console.log([...playlist]);This prints:
IntroUphillCool down[ 'Intro', 'Uphill', 'Cool down' ]Each loop calls [Symbol.iterator]() again, so each one gets a fresh iterator that starts from the first track. Keep the position inside the method, as index is here, rather than in a variable outside it, or a second loop starts where the first one stopped.
Using a generator instead
Section titled “Using a generator instead”A generator method returns an iterator for you, so the same idea takes far less code. Put * in front of the method name and yield each value:
const playlist = { name: 'Morning run', tracks: ['Intro', 'Uphill', 'Cool down'], *[Symbol.iterator]() { for (const [i, track] of this.tracks.entries()) { yield `${i + 1}. ${track}`; } },};
for (const track of playlist) { console.log(track);}This prints:
1. Intro2. Uphill3. Cool downIterator and Generator Fundamentals explains how generators pause at each yield.
Iterable classes
Section titled “Iterable classes”A class can define the same method, which makes every instance iterable. This Range class works out its values when asked rather than storing them in an array:
class Range { constructor(start, end, step = 1) { this.start = start; this.end = end; this.step = step; }
*[Symbol.iterator]() { for (let n = this.start; n <= this.end; n += this.step) { yield n; } }}
const marks = new Range(0, 100, 25);console.log([...marks]);
const [first, second] = marks;console.log(first, second);This prints:
[ 0, 25, 50, 75, 100 ]0 25Array destructuring uses the iterator too, and it stops after taking the values it needs.
Stopping early with return()
Section titled “Stopping early with return()”When a for...of loop ends before the iterator is done, because of break, return or an error, it calls the iterator’s optional return() method. That is the place to release anything the iterator holds open, such as a file or a connection:
const shelf = { books: ['Emma', 'Persuasion', 'Middlemarch'], [Symbol.iterator]() { let index = 0; const books = this.books; return { next() { return index < books.length ? { value: books[index++], done: false } : { value: undefined, done: true }; }, return() { console.log('closed early'); return { value: undefined, done: true }; }, }; },};
for (const book of shelf) { console.log(book); if (book === 'Persuasion') break;}This prints:
EmmaPersuasionclosed earlyGenerators provide return() automatically, and a finally block inside the generator runs when the loop stops early.
Steve Griffith covers this topic in his video Custom Iterators and for…of Loops.