Skip to the workspace
Pebellslearn by building
Iterators and Generators  ›  Lesson

yield and Generator Control Flow

Iterators and Generators 12 min

javascript / yield and Generator Control Flow

Explore each scene at your own pace.

01 · yield and Generator Control Flow

yield and Generator Control Flow

yield and Generator Control Flow

yield pauses a generator and produces a value for the caller. A later next(value) supplies the result of that suspended yield expression; the first next argument is ignored.

Two directions of communication happen at the pause: a yielded value leaves, and a later input can come back.

See the mechanism

Walk through the modelyield and Generator Control FlowAuthored snapshots of the example; use Run below to test the code.
yield"Your name?"
Statename not assigned yet
The first next runs up to the initial pause.
1 of 3

Follow one example

javascript

The first call reaches yield and returns the prompt. The assignment to name is not finished yet. The second call resumes that yield expression with "Anaya", allowing the assignment and next greeting yield. next("Anaya") on a brand-new generator would not supply name, because there is no suspended yield to receive it yet.

Predict, change and check

Predict: What greeting appears if the second call is next() with no argument?

Test your explanation: Try the missing input, then restore it. Finish the generator with another next and check done rather than assuming every call yields a meaningful value.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Resumption can also supply a value

The argument supplied to a later next(value) becomes the result of the suspended yield expression inside the generator. The first next argument does not supply a value to a prior yield, because none has suspended yet. Distinguish outward yielded values from inward resumption values.

yield* delegates to another iterable and can receive its completion value. Early return or throw interactions can affect cleanup, especially around finally. Trace every next result in a small example, including the final done:true result, rather than treating a generator as an array that was constructed all at once.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.