Generator Functions in JavaScript

Photo by Agê Barros on Unsplash

Generator Functions in JavaScript

Functions are the building block of every program. In JavaScript, we have a special function called Generator Function. What makes this function special? It’s an execution cycle. From the top level, it only executes till a certain part and stops further, on calling again it would continue from the instance and return if it finds the breakpoint again, this cycle continues until we add a hard stop. Now Let’s dive deep to look into the details of Generator functions.

function* generatorCreator() {
  let counter = 0;

  while(true) {
    yield counter;
    counter += 1;
  }
}

const genOperator = generatorCreator();


genOperator.next();
genOperator.next();
genOperator.next();

Let’s break down the above code. If you’ve noticed in the initial line function* — after the function there is an asterisk symbol which indicates to the JS compiler that it’s not a regular function but a Generator function. As it’s a while loop with true expression, which would execute this loop infinitely. Inside the loop yield keyword is used (this is the breakpoint that stops further executions).

The const genOperator = generatorCreator(); is where the generator object instance is initiated, the function won’t be called at this stage. Once the genOperator.next(); is called, actual function execution takes place though it would stop at the yield counter; stage. Now when the second next method is called execution resumes from the below line, the counter is updated with 1 again the loop runs going back to yield and stopping the execution further. This process would continue whenever we call the next() function making the counter update.

Generator Functions are usually used in the library codebase or customs iterators. A package like redux-saga is one the best example where it’s been used extensively.