Generator
Генератор
A generator produces one item at a time as the program asks for it. After yielding an item, it pauses and picks up where it left off when the next item is requested.
Also known as: yield
What a generator does
Suppose you need the first ten matching records from a large file. Building a list of every match means scanning the entire file before you can use the first result. A generator can hand back each match as it finds it. The caller can stop after ten, so the rest of the file need not be scanned. Producing values on demand like this is called lazy evaluation.
What happens at yield
In JavaScript, a generator function is declared with function*. Calling it creates a generator object without running the function body. The first call to .next() runs the body until it reaches yield or finishes. At yield, it hands a value to the caller and pauses, keeping its local variables and its place in the code. The next .next() resumes from that point rather than starting over.
Each .next() returns an object with value and done. A yielded value comes with done: false; normal completion produces done: true. A value supplied by return is visible in the completion result, but for...of does not treat it as another item. Python uses the same pause-and-resume idea: a function containing yield creates a generator when called, and next() raises StopIteration when the generator finishes.
Example in JavaScript
function* countdown(start) {
for (let n = start; n > 0; n--) {
yield n;
}
}
const numbers = countdown(3);
console.log(numbers.next()); // { value: 3, done: false }
console.log([...numbers]); // [2, 1]
console.log([...numbers]); // []
The spread operator consumes the remaining items, not the original sequence. Once this generator is exhausted, asking for more items will not restart it. Call countdown(3) again to get a fresh generator.
When to use one
Generators are useful for traversing a tree without first collecting every node, transforming data in stages, or describing a sequence with no fixed end. A generator is an iterator, but an iterator does not have to be a generator: you can implement the iteration protocol yourself and track the current position explicitly.
Lazy does not mean asynchronous. A synchronous generator runs when the caller requests an item, and an expensive computation before the next yield still blocks that call. If producing each item involves awaiting I/O, JavaScript also has async generators, which can be consumed with for await...of.
What interviewers ask
A typical question is whether a generator saves time or memory compared with returning an array. The answer depends on how it is consumed. Stopping early can avoid work; consuming every item still requires producing every item. Processing values one at a time can avoid storing the full result, but the generator may retain large objects in its local state, and spreading it into an array gives up the memory benefit of incremental consumption.