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.


    Delegate JavaScript (ES6) generator iteration control


    We can execute generators from generators, and delegate the iteration control with the yield* keyword.

    Yo dawg, I heard you like generators, so I put generators inside your generators.



    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




    Here, we have a very simple generator called createCounter which yields the values 1, 2, and 5. If we iterate over it with a for...of loop, it will log 1, 2, and 5. Yes, everything works as expected.

    Now, let's say we have a second generator called createThreeToFourCounter, which yields the values 3 and 4. Now, we want to put that in between the yield 2 and the yield 5, but we don't want to manually iterate over it. Thankfully, the yield keyword has something similar to the function keyword.

    If you type yield* and then a generator, in our case, createThreeToFourCounter, what happens is that this createCounter generator delegates its control to the createThreeToFourCounter. If we execute this code, notice how we didn't change anything about the for...of loop, still the exact same, but if we execute this, it actually logs all the values from 1, 2, 3, 4, to 5.

    An interesting side effect of this is that we can actually return a value from the delegated generator, and then get that value in our other generator.

    We can say const four = yield createThreeToFourCounter, and then just console.log four out manually. If we execute this, we get the exact same result as the last time, 1, 2, 3, 4, 5, but this time, we return 4 and then console.log logged it out manually. Communication between two different generators is also possible.