When we talk about iterators there are two main protocols to be aware of: iterables and iterators.
Iterables are data structures that can be iterated. Such example is array, since we can loop through every element of array.
Iterator is a simple interface for looping through data – looping through iterable.
Iterator is an object that has next() method on it.
Think collection types like Array, Map, Set etc. They all have their own iterators and they are also iterables. That means that we can iterate through each element of those types.
Lets look at code representation for Iterator and Iterable:
for..ofconstruct. Some built-in types are built-in iterables with a default iteration behavior, such as Array or Map, while other types (such as Object) are not.
In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a Symbol.iterator key:
Built-in iterable types
Some of the built-in iterable types are:
- arguments object
Example including array:
We can use for-of with arguments object:
To make sure that we have
Symbol.iterator behind the scenes:
As we mentioned earlier String is also a built-in iterable object:
Iterators and Iterator protocol
Basic implementation of iterator protocol:
Value property can be omitted once done is set to true. It represents an item from the collection while done tells us if we are done with iterating. Therefore, it will be false only once when we loop through every element.
- Iterables are data structures that can be iterated
- Iterators are objects that we use to iterate (loop through) an iterable.
- Built-in iterables:
- We use iterator.next() method to loop through elements of iterable
- iterator.next() returns us an iterator result – object that has two properties (value, done)
- for..of uses iterators behind the scenes and makes it easier for us to work with iterables
Also published on Medium.