🟨 JavaScript Intermediate

What are JavaScript generators?

Answer

Generator functions (ES6) can pause execution and resume later, yielding multiple values over time. Declared with function*. When called, they return a generator object (iterator) — the function body does not execute yet. Each call to .next() runs until the next yield, returning {value, done}. function* count() { yield 1; yield 2; yield 3; }. const gen = count(); gen.next() // {value:1, done:false}. Infinite sequences: function* ids() { let n = 0; while(true) yield n++; }. Pass values into the generator: const val = yield expression — the value passed to the next .next(val) call becomes the result of yield. Return early: gen.return(value). yield* delegates to another iterable. Generators implement the iterable protocol — use with for...of. Used for: lazy evaluation, infinite sequences, async control flow (async generators), and state machines.