DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on • Edited on

JavaScript Design Patterns - Behavioral - Iterator

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:

Top comments (11)

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

There's no need to create a non-standard wrapper around an array โ€” just use the built-in Symbol.iterator method:

const elements = [1, 2, 3, 4, 5]
const elementsIterator = elements[Symbol.iterator]()

toggleButton.addEventListener('click', () => {
    const next = elementsIterator.next()
    if (!next.done) {
        const element = next.value
        currentElement.innerText = `Current element: ${element}`
    }
})
Enter fullscreen mode Exit fullscreen mode

Or even simpler (if arguably a bit hacky):

toggleButton.addEventListener('click', () => {
    for (const element of elementsIterator) {
        currentElement.innerText = `Current element: ${element}`
        break
    }
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
thexdev profile image
M. Akbar Nugroho

Thanks for sharing, Nhan! Btw, the illustration seems came from Refactoring Guru webaite and I think a simple credit should make the author feels appreciated ๐Ÿ™Œ

Collapse
 
nhannguyendevjs profile image
Nhan Nguyen

I bought a Dive Into Design Patterns book from Refactoring.Guru ๐Ÿ˜

Image description

Collapse
 
thexdev profile image
M. Akbar Nugroho

That's awesome! I love that book also. But, I don't know if we already bought, we are allowed to use those attributes. It reminds me when I put illustration from Refactoring UI then someone suggested me to put credit because it's licenced.

Collapse
 
im_lakhlan profile image
Anil Kumar

Thank you for sharing about this website. Found very usefull

Collapse
 
oculus42 profile image
Samuel Rouse • Edited

Iterators can be an interesting topic, it can be much cleaner than creating and populating an array. It is especially helpful if you are creating an unlimited sequence or progression of numbers.

When developing an iterator, the next logical step is to look at built-in iteration protocols. Implementing these allows standard Iterable consumers like Array.from() and spread operators.

Collapse
 
oculus42 profile image
Samuel Rouse

Also, please be aware of copyright concerns when using content or illustrations from other sources.

Collapse
 
sgmonda profile image
Sergio G. Monda.

This is a non-standard approach, so custom that will not integrate well with the language capabilities. It could be useful for learning purposes but a better approach is to follow the iteration protocol. That is the standard way to hide your implementation behind something similar to your idea but compatible with forโ€ฆof loops, for instance.

Collapse
 
nicholasbalette profile image
Nicholasbalette

It's a plus is my programming ,adventure.

Collapse
 
lcuevastodoit profile image
LUIS CUEVAS • Edited

Excellent your Iterator class. Javascript classes are great. I recommend them always to fix the functional programming spaghetti

Collapse
 
sloan profile image
Sloan the DEV Moderator

This post may contain uncredited images. Failure to properly attribute all visual content violates our policies and may result in account suspension.