Generators (function*) in JavaScript
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.
yield pauses with value
function* gen() { yield 1; yield 2; } — each next() resumes after the previous yield.
State persists between
Locals survive across yields — loops and counters continue where they paused, no manual bookkeeping.
Delegate with yield*
yield* other() splices sub-sequences inline — composing generators from generators.
Send values back in
gen.next(v) makes v the paused yield's result — coroutines conversing both directions.
function* odds() { let n = 1; while (true) { yield n; n += 2; }}let g = odds();console.log(g.next().value, g.next().value);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.