Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 971 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Iterate over JavaScript (ES6) generators

1:01 JavaScript lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

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 counter.next 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.

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