Iterator and Generator
On this page
#Iterator
In JavaScript, an iterator is an object that allows you to traverse a collection one element at a time by conforming to the iterator protocol.
#The Iterator Protocol
To be a valid iterator, an object must implement a next() method. Each time next() is called, it returns an IteratorResult object containing two properties:
value: The current data element in the sequence.done: A boolean that isfalseduring iteration and becomestrueonce the sequence finishes.
Here is a basic manual implementation:
const myIterator = {
data: [10, 20],
index: 0,
next() {
if (this.index < this.data.length) {
return { value: this.data[this.index++], done: false };
}
return { value: undefined, done: true };
}
};console.log(myIterator.next()); // { value: 10, done: false }
console.log(myIterator.next()); // { value: 20, done: false }
console.log(myIterator.next()); // { value: undefined, done: true }# Iterators vs. Iterables
While an iterator is the mechanism that fetches values, an iterable is an object that makes itself accessible to loops like for...of.
#Building an Iterator from a Generator
const generatorFunction = function* () {
// This does not get executed.
console.log('a');
};console.log(1);
const iterator = generatorFunction();
console.log(2);
// 1
// 2#Advancing the Generator
next() method is used to advance the execution of the generator body:
const generatorFunction = function* () {
console.log('a');
};console.log(1);
const iterator = generatorFunction();
console.log(2);
iterator.next();
console.log(3);
// 1
// 2
// a
// 3next() method returns an object that indicates the progress of the iteration:
const generatorFunction = function* () {};
const iterator = generatorFunction();
console.log(iterator.next());
// Object {value: undefined, done: true}done property indicates that the generator body has been run to the completion.
The generator function is expected to utilize yield keyword. yield suspends execution of a generator and returns control to the iterator.
const generatorFunction = function* () {
yield;
};
const iterator = generatorFunction();
console.log(iterator.next());
console.log(iterator.next());
// Object {value: undefined, done: false}
// Object {value: undefined, done: true}When the generator is advanced to the completion, the return value is returned.
const generatorFunction = function* () {
yield 'foo';
return 'bar';
};const iterator = generatorFunction();
console.log(iterator.next());
console.log(iterator.next());
// Object {value: "foo", done: false}
// Object {value: "bar", done: true}