Generators with function*
Generators with function* in Modern JavaScript
While custom iterators are powerful, manually managing state variables and returning { value, done } boilerplate can be tedious. Generators—defined using the function* syntax and the yield operator—provide a clean, stateful way to define iterative algorithms.
1. Syntax & Core Mechanics
A generator function returns a Generator object, which conforms to both the Iterable and Iterator protocols simultaneously:
2. Infinite Generators & Lazy Evaluation
Because generators pause until next() is explicitly called, they can represent infinite sequences without consuming infinite memory (Lazy Evaluation):
3. Two-Way Communication: Passing Values into next(value)
The yield keyword is not only an output statement—it can also receive inputs passed to gen.next(arg):
4. Delegating Generators with yield*
The yield* operator delegates iteration to another generator or iterable:
Practice Quiz
Using console methods
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Creating Custom Iterators | Using console methods |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.