Iterator
Last updated
Last updated
Iterator is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.).
The Iterator pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
In JavaScript, iterators are widely used and are part of the language itself, introduced in ES6 with the concept of iterables and iterators.
In this example:
We have an iterableObject
with an array of items.
We define the [Symbol.iterator]
method on the iterableObject
, which returns an iterator object conforming to the iterator protocol.
The iterator object has a next
method that returns the next item in the sequence each time it's called.
It returns an object with value
and done
properties.
We obtain the iterator using iterableObject[Symbol.iterator]()
and then loop through it until done
becomes true
, logging each item to the console.
This pattern allows us to abstract away the internal structure of the object (iterableObject
in this case) and provide a consistent way to iterate over its elements, making the code more modular and maintainable.