Join egghead, unlock knowledge.

Want more egghead?

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

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Iterate over JavaScript (ES6) generators


    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 Pro 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
    orLog In




    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.

    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.