Understand Each Iteration Inside a Generator

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet

A clear understanding of how iterations are defined and execute inside a generator is essentially to being able to use them properly. Each next call on the iterator runs inside the generator until it reaches a yield statement then the generator pauses until next is called again. When a next is called and no yield is found, then the generator assumes it is done.

John Lindquist: [0:00] After each yield a generator pauses execution. If I yield 1 and console.log("one"), and then I iterate to the next, console.log(iterator.next()), hit save, you'll see a log out the value of "one" and done false, but it does not log out console.log("one"). Our first iteration starts here and ends here. To trigger anything after yield 1, so in our case this console log, would be our second iteration and that second iteration isn't fired off until we iterator.next(), again.

[0:38] If I hit save now, we'll get a yield of 1 from our first interaction, and from the second iteration it starts logging out console.log("one") and then returns an undefined with a done of true. If we were to yield out 2 right here and try and console.log("two"), you'd see that we'd get the first yield of 1 then console logging "one" from the second iteration, then it yields out 2, but then it never logs out console.log("two"), because it never gets that far.

[1:13] When working with generators it's important to keep the mindset of iterations, where this is a first iteration, so the first .next we'll call this. This is the second iteration I'm going to type in second here just so that's more clear.

[1:26] Everything up until here gets evaluated and then everything after here is the third iteration which has not been called yet because we haven't called next. But if we do call next, and we'll finally get out this third iteration, but it'll return the value of undefined because we haven't yielded anything.

[1:46] This next fires off this, this next fires off this, we'll add some space for clarity. That's more space here, this next fires off this. Since we're not yielding anything in this third iteration, it's considering it to be done.