Create Your First Generator in JavaScript

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

With a solid understanding of iterators, seeing the benefits of using generators becomes much more obvious. Generators allow us to write iterators with a much more concise syntax and give us more flexibility with each iteration.

Instructor: [0:00] With an understanding of creating a custom reverse iterator, let's refactor this using a generator. We'll call this reverseIterator. The generator syntax uses a * right after function. We'll just go ahead and take all the pieces from above and use them inside of our reverseIterator, which is the generator this time.

[0:23] The only thing we've done so far is just added a * here, which will give us the ability to use some new syntax. I'm going to take this array, copy and paste it down to here, then I'll take this array length, copy and paste it down to here. I'll take the done value, put that inside of a while loop, and I'll take the value value and paste that inside of the while loop.

[0:48] Now the special syntax that this * affords us is the ability to use yield, which will push out the value following yield each time it steps through. Now instead of create reverseIterator, we can just copy and paste reverseIterator, paste that right here, hit save, and you'll notice this didn't work. It didn't print out anything, because there is one difference between this done and this done.

[1:17] This done is telling it to keep going until this is true, so keep going while it's false, but what we need to do here is to say keep going while this is true and then stop when it's false. We just have to flip that sign there, hit save, and we get 3, 2, and 1. This generator* here allows us to write a much more concise syntax, which mirrors what's going on here.

[1:48] The value being pushed out just follows whatever you say yield is. The done can mostly be thought of as the expression that goes inside of a while loop or something that's telling it to yield.

[2:00] The statefulness of the i is just the exact same. The ability to pass in some sort of value to iterate over is a native feature of generators, whereas with a iterator we created by hand, we had to set up a function which wrapped the creation of this object.

[2:18] Using the generator saved us a lot of typing and a lot of mental overhead, where we only have to think about what we're starting, when it should keep going, and what it's pushing out.