Generators in ES6

Generators are a new feature in ES6. You declare a generator function which returns generator objects g that can then be iterated using any of Array.from(g), [...g], or for value of g loops. Generator functions allow you to declare a special kind of iterator. These iterators can suspend execution while retaining their context.
Here is an example generator function. Note the * after function. That’s not a typo, that’s how you mark a generator function as a generator.

function* generator () {
  yield 'f'
  yield 'o'
  yield 'o'

A quick overview of Generators:

  • Generator functions are a special kind of iterator that can be declared using the function* generator () {} syntax
  • Generator functions use yield to emit an element sequence
  • Generator functions can also use yield* to delegate to another generator function — or any iterable object
  • Generator functions return a generator object that’s adheres to both the iterable and iterator protocols
    • Given g = generator(), g adheres to the iterable protocol because g[Symbol.iterator] is a method
    • Given g = generator(), g adheres to the iterator protocol because is a method
    • The iterator for a generator object g is the generator itself: g[Symbol.iterator]() === g
  • Pull values using Array.from(g), [...g], for (let item of g), or just calling
  • Generator function execution is suspended, remembering the last position, in four different cases
    • A yield expression returning the next value in the sequence
    • A return statement returning the last value in the sequence
    • A throw statement halts execution in the generator entirely
    • Reaching the end of the generator function signals { done: true }
  • Once the g sequence has ended, simply returns { done: true } and has no effect
  • It’s easy to make asynchronous flows feel synchronous
    • Take user-provided generator function
    • User code is suspended while asynchronous operations take place
    • Call, unsuspending execution in user code

I highly recommend you go over Axel’s article on generators, as he put together an amazing write-up on use cases for generators just a few months ago.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s