Generator Functions

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.

Illustration of Generator Functions
Illustration of Generator Functions

💡 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 yield to pause and send values back to the caller
  • Execution can be resumed with the next() method

📌 Deep Dive: Basic Generator Function

JAVASCRIPT
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 }
Output
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: undefined, done: true }

How it works:

  • Each yield outputs a value, then pauses the function
  • Calling next() resumes execution until the next yield or function end
  • The done property indicates if the generator has finished

💡 Generator Object Methods

  • next(value): Resumes execution, optionally sending a value into the generator
  • return(value): Ends generator and returns a value
  • throw(error): Throws an error inside the generator
Generator Methods Comparison
MethodPurpose
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

JAVASCRIPT
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 }
Output
{ value: "What's your name?", done: false }
{ 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 yield to output intermediate values
  • Generators support custom iteration and controlled data production