×

javascript · level 3 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A function pauses at every .

Writing next() by hand is fiddly. A generator writes it for you. Put a star after function and, inside, yield each value in turn. Calling the generator runs nothing yet: it hands back an iterator.

Each next() runs the body as far as the next yield, hands that value out and freezes on the spot, local variables and all. When the body ends, done becomes true. Generators are iterable, so for...of and spread work too.

function* trafficLight() {
  console.log("starting");
  yield "red";
  yield "amber";
  yield "green";
}
const light = trafficLight();
console.log("made it");
console.log(light.next().value);
console.log([...light]);

Spread carries on from wherever the generator paused, so it only collects amber and green.