Intermediate JavaScript Interview QuestionsIntermediateConcept
JavaScript · Question 66
What are generator functions, and how do yield and next() work?
Direct answer
A generator function declared with function* returns a generator object; execution can pause at yield and later resume when next() is called, making generators useful for lazy iteration and controllable sequences.
Calling a generator function does not execute its body to completion immediately. It returns a generator object. The first next() begins execution until a yield (or return/end), producing an iterator result.
For function* ids(){ yield 1; yield 2; }, repeated next() calls produce values 1 and 2, then a result with done: true.
- Generators work naturally with
for...ofand spread because generator objects implement the iteration protocols. - A value passed to a later
next(value)can become the result of the suspendedyieldexpression inside the generator. return()andthrow()allow consumers to influence generator completion/error flow.- Use generators when laziness or pull-based iteration clarifies the model; do not replace simple array transformations with generators purely for cleverness.