Published on

Generator Function in Javascript

Javascript: Generator Function

In JavaScript, a generator function is a special type of function that can be used to generate a sequence of values. This is accomplished by using the yield keyword within the function. Unlike a regular function, a generator function does not return a single value, but rather returns a generator object that can be used to produce a sequence of values.

What is the Syntax of Generator Function?

Here is an example of a simple generator function:

function* numbers() {
  yield 1;
  yield 2;
  yield 3;

How to use generator function?

To use this generator function, we can create a generator object by calling the function with the new keyword, like this:

const generator = new numbers();

Once we have a generator object, we can use it to generate values from the sequence by calling the next() method on the generator object. This will return an object with two properties: value, which is the next value in the sequence, and done, which is a boolean value that indicates whether the generator has reached the end of its sequence.

Here is an example of how we can use the next() method to generate values from the numbers generator function:

const generator = new numbers();

console.log(; // { value: 1, done: false }
console.log(; // { value: 2, done: false }
console.log(; // { value: 3, done: false }
console.log(; // { value: undefined, done: true }

Where can we use Generator Function?

  1. One common use case for generator functions is to create iterators for complex data structures. For example, we could use a generator function to create an iterator for a tree data structure, which would allow us to easily traverse the tree and access its values in a sequential manner.

  2. Another use case for generator functions is to implement asynchronous programming techniques, such as coroutines. By using yield statements within a generator function, we can pause the execution of the function and resume it at a later time, which allows us to write asynchronous code in a more synchronous-looking style.