JavaScript Generator Functions
Subject: JavaScript
A Generator Function in JavaScript is a special type of function that can pause its execution and resume later. It is defined using the function* syntax and uses the yield keyword to pause execution.
What Is a Generator?
A generator function:
- Does not run to completion immediately
- Returns a generator object when called
- Can pause at each
yieldstatement - Can be resumed using the
.next()method
Syntax
Example 1: Simple Generator
Each call to .next() resumes execution until the next yield.
Example 2: Generator with Loop
Example 3: Passing Data to yield
Generator Methods
Generators support .next(), .return(), and .throw() methods for controlling execution.
Example 4: Generator with return() and throw()
Use Cases of Generators
- Lazy iteration (e.g., reading large data step-by-step)
- Creating custom iterable data structures
- Asynchronous control flow management
- State machines
- Pausable computations like animations or games
Key Takeaways
- Declared with
function*and useyieldto pause execution. - Calling a generator returns an iterator with
.next(),.return(), and.throw(). - Useful for custom iteration, async programming, and complex control flow.
- Can be iterated using
for...ofloops over yielded values.