What is a Generator Function in JavaScript?

A generator function is a special kind of function that can be paused and resumed, allowing it to yield multiple values over time. Unlike regular functions that execute from start to finish, generator functions return an iterator object that can be used to manually control the function's execution.

What is a Generator Function in JavaScript?

A generator function is a special kind of function that can be paused and resumed, allowing it to yield multiple values over time. Unlike regular functions that execute from start to finish, generator functions return an iterator object that can be used to manually control the function’s execution.

Syntax:

  • Defined using the function* syntax (the asterisk * after function).

  • Uses the yield keyword to pause the function and return a value.

  • Resumed with the next() method.

function* generatorFunction() { yield “Hello”; yield “World”; }

const gen = generatorFunction();
console.log(gen.next()); // { value: "Hello", done: false }
console.log(gen.next()); // { value: "World", done: false }
console.log(gen.next()); // { value: undefined, done: true }

Why Use Generator Functions?

  • Lazy Evaluation: Generates values on demand rather than computing them all at once.

  • Memory Efficiency: Doesn’t store all values at once, reducing memory usage.

  • Control over Execution: Can pause and resume function execution, which is not possible with regular functions.

  • Asynchronous Programming: Can simplify async operations when combined with yield and Promises.

  • Infinite Sequences: Generate an infinite sequence of values without crashing the system.

How Does a Generator Work?

A generator function returns an iterator. You use the next() method to:

  1. Move to the next yield.

  2. Get the value returned by the current yield.

  3. Know if the generator has completed (done: true).

function* count() {
  let i = 0;
  while (true) {
    yield i++;
  }
}

const counter = count();
console.log(counter.next().value); // 0
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
function* iterateArray(arr) {
  for (const item of arr) {
    yield item;
  }
}

const iterator = iterateArray(["Apple", "Banana", "Cherry"]);
console.log(iterator.next().value); // Apple
console.log(iterator.next().value); // Banana
console.log(iterator.next().value); // Cherry
function* asyncTask() {
  const user = yield fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json());
  console.log("User:", user);
}

const iterator = asyncTask();
const promise = iterator.next().value;

promise.then((user) => iterator.next(user));

When to Use Generators:

  • Lazy Iteration: Generating values on demand.

  • Infinite Sequences: Creating endless data streams efficiently.

  • Async Flow Control: Simplifying asynchronous code.

  • Data Streaming: Handling large data sets without loading them entirely.

  • Custom Iterators: Creating iterable objects.

Generators offer a powerful way to handle scenarios where you need to manage multiple values over time, rather than all at once

ad ad