JavaScript Design Patterns - Behavioral - Iterator

Nhan Nguyen - Jun 10 - - Dev Community

The iterator pattern allows us access to the elements in a collection without exposing its underlying representation.

In the example below, we will create a simple iterator with an array of elements. We can iterate through all the elements using the methods next() and hasNext().

class Iterator {
  constructor(el) {
    this.index = 0;
    this.elements = el;
  }

  next() {
    return this.elements[this.index++];
  }

  hasNext() {
    return this.index < this.elements.length;
  }
}
Enter fullscreen mode Exit fullscreen mode

A complete example is here 👉 https://stackblitz.com/edit/vitejs-vite-2txuqu?file=iterator.js

🚀 Using this pattern when we want to access an object’s content collections without knowing how it is internally represented.


I hope you found it helpful. Thanks for reading. 🙏

Let's get connected! You can find me on:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .