Skip to content

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.

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:

Intro
Uphill
Cool 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.

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. Intro
2. Uphill
3. Cool down

Iterator and Generator Fundamentals explains how generators pause at each yield.

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 25

Array destructuring uses the iterator too, and it stops after taking the values it needs.

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:

Emma
Persuasion
closed early

Generators 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.