Anton Petrov interesting article about iteration protocols. Iterables and Iterators are not built-ins or syntactic sugar introduced by some recent ECMAScript standard, but protocols that were defined in the ECMAScript’s 6th edition.
Iterables and Iterators can be implemented by almost any object following some rules and conventions.
Generator, on the other hand, is a new built-in object, returned by a new kind of function: the generator function. This object conforms to both protocols.
So with ES2015+ we have the power to design a way for our objects to iterate through their values.
Do not reuse generators! Even if the for…of loop is terminated early, for example via the break keyword. Upon exiting a loop, the generator is closed and trying to iterate over it again does not yield any further results.
More in the article, which in detail describes:
- The Iterable protocol
- How to create your own Iterable
- The Iterator protocol
- How to create an Iterator
- What are Generators
Good read!
[Read More]