Falak
WebDevelopment

Iterator and Generator

1 min read

#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 is false during iteration and becomes true once the sequence finishes.

Here is a basic manual implementation:

JS
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 };
  }
};
JS
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

JS
const generatorFunction = function* () {
    // This does not get executed.
    console.log('a');
};
JS
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:

JS
const generatorFunction = function* () {
    console.log('a');
};
JS
console.log(1);
const iterator = generatorFunction();
console.log(2);
iterator.next();
console.log(3);
 
// 1
// 2
// a
// 3

next() method returns an object that indicates the progress of the iteration:

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

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

JS
const generatorFunction = function* () {
    yield 'foo';
    return 'bar';
};
JS
const iterator = generatorFunction();
 
console.log(iterator.next());
console.log(iterator.next());
 
// Object {value: "foo", done: false}
// Object {value: "bar", done: true}

Share this post