Iterate over JavaScript (ES6) generators

Max Stoiber
InstructorMax Stoiber
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

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.

[00:00] 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.

[00:30] 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.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today