This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Delegate JavaScript (ES6) generator iteration control

1:48 JavaScript lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

Avatar
Mher

Oh my that's too complicated...

In reply to egghead.io
Avatar
Vamshi

Can you help me understand how 3 was consoled out when we returned only 4?

Avatar
Anshuman

Because of the

yield 3

line in create3To4Counter()

In reply to Vamshi

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?