JavaScript Design Patterns — Behavioral — Iterator
Jun 10, 2024
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;
}
}
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs