More on ES6 part 2
Iterators & Generators
Symbol.iterator is the default iterator for an object. The for...of loops are based on this type of iterator.
In the example below, we will see how we should implement it and how generator functions are used.
Example:
First, we create an object, and use the Symbol.iterator and generator function to fill it with some values.
In the second line of the code, we use a * with the function keyword. It's called a generator function (or gen function).
For example, here is a simple case of how gen functions can be useful:
We can exit and re-enter generator functions later. Their variable bindings (context) will be saved across re-entrances. They are a very powerful tool for asynchronous programming, especially when combined with Promises. They can also be useful for creating loops with special requirements.
We can nest generator functions inside each other to create more complex structures and pass them arguments while we are calling them.
The example below will show a useful case of how we can use generator functions and Symbol.iterators together.
Example:
We create an object of 7 elements by using Symbol.iterator and generator functions. In the second part, we assign our object to a constant all. At the end, we print its value.
Tap Try It Yourself and follow the instructions in the comments to see the results.
Comments
Post a Comment