Advanced 12 min

Iterables and generators

An iterable can hand its values to a for-of loop, and a generator supplies them one at a time.

How it works

The first request to a generator runs until the first yield. The next request continues after that yield. This lets you create a sequence without storing its complete contents. It also explains why spreading the same exhausted iterator a second time gives no more values.

Walk through an example

A generator function uses function* and pauses at each yield. Spreading the generator consumes the yielded values into a new array.

What to watch for

For large or infinite sequences, avoid spreading the whole generator into an array. Take only the values you need.

Code example

function* pair() {
  yield 4;
  yield 7;
}
console.log([...pair()]);

Check your understanding

What array does [...generator()] produce?

See the example and explanation
Worked example
Given A generator yields 4 and then 7.
Answer [4, 7]

The spread operation repeatedly asks for the next value until the generator finishes.

Open practice problem
Next lessonWeb workers and message passing