Lazy sequences
Produce sequence values only as consumers request them, avoiding eager creation of the full sequence.
JavaScript · Type Alias
A Generator is the iterator object produced by a generator function. It combines iterable and iterator behavior, allowing execution to pause at yield and resume later.
A Generator is the iterator object produced when a generator function is called. It pauses at each yield, resumes through next(), and also supports throw() and return(); because it implements both iterator and iterable protocols, it can be used with for...of and spread syntax.
function* name(param0, param1, /* …, */ paramN) {
statements
}A generator function call returns a new Generator object.
function* numbers() {
yield 1;
yield 2;
}
const generator = numbers();
console.log(generator.next()); // { value: 1, done: false }
console.log([...generator]); // [2]A generator function call creates a Generator that yields values on demand and can be consumed with iterator operations or for...of.
Produce sequence values only as consumers request them, avoiding eager creation of the full sequence.
Represent an unbounded or computationally expensive sequence without calculating every value in advance.
Expose custom iteration behavior through for...of, spread syntax, and other iterable consumers.
Pause an algorithm and exchange values bidirectionally between the generator and its caller.
A Generator is an object returned by calling a generator function. It conforms to both the iterator and iterable protocols, so it provides iterator control methods and can be consumed by iteration constructs.
Follow-up: How does it differ from an ordinary function? A generator function suspends and later resumes execution around yield, while an ordinary function runs to completion when called.
next() resumes the suspended generator and returns an iterator-result object containing value and done. The yielded expression supplies value while done indicates whether iteration has finished.
Follow-up: What does passing an argument to next() do? After the first resume, that argument becomes the result of the currently suspended yield expression.
return() finishes the generator as though a return statement were inserted at its current suspended position. This lets generator cleanup run when the body uses try...finally.
Follow-up: How can an error be injected? throw() resumes the generator by throwing an exception at its suspended position, allowing generator code to catch or propagate it.
Generator.prototype.next()Generator.prototype.return()Generator.prototype.throw()GeneratorFunctionIteratorfunction*yieldyield*