...

/

Implementing an Iterator

Implementing an Iterator

Learn how to create an iterator and discuss the process flow with a diagram and example.

Iterator to make an object iterable

To satisfy JavaScript and allow iteration over an instance of a class like CardDeck, we need to create a method to serve as an iterator.

However, this is easier said than done. Buckle your seat belts before looking at the code.

Press + to interact
class CardDeck {
constructor() {
this.suitShapes = ['Clubs', 'Diamonds', 'Hearts', 'Spaces'];
}
[Symbol.iterator]() {
let index = -1;
const self = this;
return {
next() {
index++;
return {
done: index >= self.suitShapes.length,
value: self.suitShapes[index]
};
}
};
}
}

The code implements a method with the special name [Symbol.iterator]. This is the good news.

📝Note: JavaScript looks for [Symbol.iterator] to be present in an instance to use that instance as an iterator.

Unfortunately, the code is very verbose and has many levels of nesting, enough to drown us. We have to hang on to those }s and climb to safety; we’ll revisit this method shortly after some preparation.

We will significantly improve this code shortly. Don’t feel perturbed at the sight of its verbosity—you almost never have to write such code thanks to generators, which you will see in the Removing Noise ...

Access this course and 1400+ top-rated courses and projects.