Skip to main content

Command Palette

Search for a command to run...

JS Generator Functions

A Quick Intro

Published
•2 min read•View as Markdown
JS Generator Functions

What are generator functions?

These are the functions that can be stopped midway and then continue from where they had stopped.

Generator functions are declared with the function*

function* generator(){
}

What do they exactly do?

In normal functions, we use the return keyword to return a value as soon as the return statement gets executed.

In the case of generator functions, the function used does not execute the code, instead, they return a generator object. This generator object handles the execution.

Object [Generator] {}

The generator object consists of the next(). This action triggers the code to run until it encounters the closest yield statement, which then produces the associated yield value.

function* generatorFun(){
  let count = 0;
  for (let i = 0; i < 2; i++) {
      count++;
      yield i;
  }
  return count;
}

let iterator = iteratorFunc();
console.log(iterator.next()); 
console.log(iterator.next()); 
console.log(iterator.next());

The next() returns an object

{value: 0, done: false}
{value: 1, done: false}
{value: 2, done: true}

One of the use cases of generator functions can be seen as creating an infinite array or creating unique identifiers.

You can go through these articles. To look more in depth

https://dev.to/rfornal/use-cases-for-javascript-generators-1npc

https://betterprogramming.pub/javascript-generators-practical-use-cases-945d512ef252


Great you have read the article till the end.

Do comment on the output of the following code.

function* genFunc(){
  yield 3;
  yield 4;
}
genFunc().next();
genFunc().next();