Learn JavaScript
❯ collections.generators

Generators (function*) in JavaScript

$concept

Generators (function* with yield) produce pausable sequences: each next() runs to the next yield, returns its value, and suspends with state intact — lazy streams, infinite series, and step-wise algorithms without manual state machines. yield* delegates to sub-generators, composing streams.

Two-way communication flows back through next(value) (becoming the yield expression's result), and .return()/.throw() terminate or inject from outside. Async generators (async function*) extend the model to awaited streams.

$how it works
1

yield pauses with value

function* gen() { yield 1; yield 2; } — each next() resumes after the previous yield.

2

State persists between

Locals survive across yields — loops and counters continue where they paused, no manual bookkeeping.

3

Delegate with yield*

yield* other() splices sub-sequences inline — composing generators from generators.

4

Send values back in

gen.next(v) makes v the paused yield's result — coroutines conversing both directions.

$example
function* odds() {
let n = 1;
while (true) {
yield n;
n += 2;
}
}
let g = odds();
console.log(g.next().value, g.next().value);
Output
1 3
1The infinite loop is safe — execution suspends at each yield indefinitely.
2First next() yields 1, second resumes past it to yield 3.
3Lazy infinite sequences consumed finitely — pull, don't push.
$use cases
Lazy infinite series (odds, fibonacci, id streams)
Step-wise algorithms pausable between phases
Composing streams with yield* delegation
Two-way coroutine conversations via next(value)

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.