Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.


    Iterate over JavaScript (ES6) generators

    Max StoiberMax Stoiber

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    00:00 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 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.

    00:30 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.