Skip to the content

Endless sequences

JavaScript · Unit 16: Iterators and generators

A generator can go on forever: a while (true) inside it hands over values for as long as they're asked for. It doesn't get stuck, because it only works when someone asks.

The one that has to stop is whoever loops over it, with a break. Without that break, the program really does hang.

function* naturals() {
  let n = 1;
  while (true) {
    yield n;
    n++;
  }
}
for (const n of naturals()) {
  if (n > 3) break;
  console.log(n);
}

Prints

1
2
3

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 blank so it adds up the numbers to 4 and then stops.

  3. 3. Predict the output

    What does this code print?

  4. 4. Predict the output

    What does this code print?

  5. 5. Find the bug

    It should print the first three even numbers: 2, 4 and 6. Which line has the bug?

  6. 6. Complete the code

    Fill in the blank so the generator hands over odd numbers for as long as they're asked for.

  7. 7. Multiple choice

    naturals() hands over 1, 2, 3… and never ends. What happens if you write [...naturals()]?

  8. 8. Find the case that fails

    takeEvens(xs, n) should return the first n even numbers in xs, or however many there are if there are fewer than n. Which call breaks it?

  9. 9. Multiple choice

    What does this generator hand over?

  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 →