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.
Tired of Poor JavaScript Skills? Fix That With Deep Grasping!Learn More





