Generator functions are a special type of function in JavaScript that can pause execution and later resume, allowing you to produce a sequence of values on demand.

💡 What is a Generator Function?
A generator function is declared with function* syntax and uses the yield keyword to pause and resume execution.
Key characteristics:
- Defined with an asterisk:
function* name() { } - Returns a Generator object when called
- Use
yieldto pause and send values back to the caller - Execution can be resumed with the
next()method
📌 Deep Dive: Basic Generator Function
function* countUp() {
yield 1;
yield 2;
yield 3;
}
const generator = countUp();
console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: undefined, done: true }
How it works:
- Each
yieldoutputs a value, then pauses the function - Calling
next()resumes execution until the nextyieldor function end - The
doneproperty indicates if the generator has finished
💡 Generator Object Methods
next(value): Resumes execution, optionally sending a value into the generatorreturn(value): Ends generator and returns a valuethrow(error): Throws an error inside the generator
| Method | Purpose |
|---|---|
| next() | Resume generator, returns next yielded value |
| return() | Stops generator, optionally returns a value |
| throw() | Injects an error inside the generator |
📌 Deep Dive: Passing Values into Generator
function* greet() {
const name = yield "What's your name?";
yield `Hello, ${name}!`;
}
const gen = greet();
console.log(gen.next()); // { value: "What's your name?", done: false }
console.log(gen.next('Alice')); // { value: "Hello, Alice!", done: false }
console.log(gen.next()); // { value: undefined, done: true }
{ value: "Hello, Alice!", done: false }
{ value: undefined, done: true }
Notice how the first next() call starts the generator, and the value passed into the second next('Alice') call becomes the result of the yield expression.
⚠️ Important
The first call to next() always starts the generator and cannot receive a value. Passing a value to the first next() is ignored.
💡 Use Cases for Generator Functions
- Implementing lazy sequences or infinite data streams
- Controlling asynchronous flows (before async/await)
- Custom iteration protocols
Summary:
- Generator functions enable pausing and resuming execution
- Use
yieldto output intermediate values - Generators support custom iteration and controlled data production
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What keyword is used inside a generator to pause execution and return a value?
Question 2 of 2
Which method resumes a generator's execution and receives an optional value?
Loading results...