A generator function is a specialized function in JavaScript that can pause its execution context and resume it at a later time. Unlike standard functions that run to completion (run-to-completion semantics) and return a single value, generator functions yield multiple values sequentially on demand, maintaining their internal state, local variables, and lexical bindings across pauses. When invoked, a generator function does not execute its body immediately. Instead, it returns a Generator object, which conforms to both the Iterable and Iterator protocols.Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Syntax
A generator function is defined using thefunction* declaration (or expression) and utilizes the yield keyword to pause execution.
Execution Mechanics
Execution of the generator’s body is controlled by thenext() method of the returned Generator object.
- Calling
.next()starts or resumes execution until it encounters ayieldexpression. - The generator pauses, and
.next()returns an IteratorResult object with two properties:value: The evaluated expression following theyieldkeyword.done: A boolean indicating whether the generator has completed execution (trueif areturnstatement is reached or the end of the function is hit).
Two-Way Communication
Theyield keyword is an expression that evaluates to a value. By passing an argument to the .next() method, the caller can inject data back into the generator’s execution context. The injected value becomes the evaluated result of the currently paused yield expression.
Note: An argument passed to the very first .next() call is ignored, as there is no previously paused yield expression to receive it.
Generator Delegation (yield*)
The yield* expression delegates execution to another generator or iterable object. The outer generator pauses and yields all values from the delegated iterable until it is exhausted, at which point the outer generator resumes.
Lifecycle Control Methods
In addition to.next(), the Generator object exposes two methods to forcefully alter the generator’s lifecycle from the outside:
Generator.prototype.return(value): Prematurely terminates the generator. It acts as if areturn value;statement was executed at the current suspendedyieldpoint.Generator.prototype.throw(exception): Injects an exception into the generator at the suspendedyieldpoint. If the generator has atry...catchblock surrounding theyield, it can catch the exception and continue; otherwise, the exception propagates out, and the generator terminates.
Master JavaScript with Deep Grasping Methodology!Learn More





