techStackGuru

JavaScript Generator


Generator functions allow you to control the iterative execution of functions in JavaScript. You can pause and resume the function's execution, yielding values one by one, making it an excellent choice for handling asynchronous operations and handling large data sets.

In order to create a generator function, you use the function* syntax. Every time you call the generator function, it runs until a yield statement is encountered and is paused, returning the yielded value. As a result, you can continue to process the generator incrementally later on.

Example

function* numberGenerator() {
    let number = 1;
    while (true) {
      yield number;
      number++;
    }
  }
  
  // Create an instance of the generator
  const generator = numberGenerator();
  
  // Generate the first 5 numbers
  console.log(generator.next().value); // Output: 1
  console.log(generator.next().value); // Output: 2
  console.log(generator.next().value); // Output: 3
  console.log(generator.next().value); // Output: 4
  console.log(generator.next().value); // Output: 5 

This example shows how the numberGenerator function produces an infinite sequence of numbers starting from 1. When you call generator.next(), it resumes the generator function and returns an object with the value property representing the value yielded.

You can perform asynchronous operations or iterate over large datasets with generator functions without having to load everything into memory at once. It can be very useful for handling asynchronous tasks or processing streams of data in a readable and manageable way.

Example 2: Fibonacci Sequence Generator

function* fibonacciGenerator() {
    let prev = 0;
    let current = 1;
    while (true) {
      yield current;
      const next = prev + current;
      prev = current;
      current = next;
    }
  }
  
  const fibonacciIterator = fibonacciGenerator();
  console.log(fibonacciIterator.next().value); // Output: 1
  console.log(fibonacciIterator.next().value); // Output: 1
  console.log(fibonacciIterator.next().value); // Output: 2
  console.log(fibonacciIterator.next().value); // Output: 3
  // Continues indefinitely, generating Fibonacci numbers one after another 

Example 3: Range Generator

function* rangeGenerator(start, end) {
    for (let i = start; i <= end; i++) {
      yield i;
    }
  }
  
  const rangeIterator = rangeGenerator(5, 10);
  console.log(rangeIterator.next().value); // Output: 5
  console.log(rangeIterator.next().value); // Output: 6
  console.log(rangeIterator.next().value); // Output: 7
  console.log(rangeIterator.next().value); // Output: 8
  console.log(rangeIterator.next().value); // Output: 9
  console.log(rangeIterator.next().value); // Output: 10
  console.log(rangeIterator.next().value); // Output: undefined (done is true)