Skip to the content

Generators

JavaScript · Unit 16: Iterators and generators

So far you looped over things that already existed. With function* (with an asterisk) you write who hands over the values: each yield lets one go.

That's a generator, and you loop over it with a for...of like any other iterable.

function* days() {
  yield "monday";
  yield "tuesday";
}
for (const d of days()) {
  console.log(d);
}

Prints

monday
tuesday

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blanks for the 5 times table generator; the loop below adds up its first three multiples.

  3. 3. Predict the output

    What does this code print?

  4. 4. Predict the output

    What does this code print?

  5. 5. Multiple choice

    A generator has already handed over all of its yields. What does the next next() return?

  6. 6. Complete the code

    Fill in the blank so both colors end up in the array.

  7. 7. Predict the output

    What does this code print?

  8. 8. Find the bug

    It should print both colors, one per line. Which line has the bug?

  9. 9. Put the lines in order

    Build a generator that hands over the numbers from 1 to n, and collect the ones from count(3) into an array.

  10. 10. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →