Generators are iterables, meaning we can easily iterate over the yielded values with a for-of loop. This video demonstrates this based on a simple counter example.
We have a very simple generator here, which yields values from 1 through 4. To get all of the values, we might do something like this. We call console.log counter.next five times, basically until the result says done is true. If we run this, you will see this works, but it's not very nice. We get through all the values and the last value we get says done true, but doing this manually is a bit tedious.
Now, we could manually build a while loop to iterate over this, but there's an easier way. ES6 includes this very nice feature called a for-of loop, so we can go for let i of counter, and then just console.log i out. When we run this, this does exactly what we needed it to do. The for-of loop pauses and resumes the generator automatically, and passes us back the values that the generator yields.
You must be a Pro Member to view code
Access all courses and lessons, track your progress, gain confidence and expertise.