All About the ‘Generator’ Function in Javascript

The generator function in javascript works the same as our real-life generator, in general, what we do, we use it while it is required, when there is electricity failure, we start the generator and use it, the Generator function also works the same, we keep function ready by assigning it to the iterator and execute it while it is needed.

In short, we are keeping the resource ready, and using it while it is required.

Generator function in javascript is a very interesting concept, this is the special type of function which allows us to pause the execution middle of the function and again play (execute) from where it is stopped.

Generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. Generator functions are written using the function*syntax.

Generator functions do not directly execute their code. Instead, it will return a special type of iterator, called a Generator. When a value is consumed by calling the generator’s next method, the Generator function executes until it encounters the yield keyword. and return the object with value and done.

value : The next value in the iteration sequence.

done : This is true if the last value in the sequence has already been consumed.

Example 1.

Every Generator has 3 In-build methods which are inherited from its prototype you can see in the below image inside the prototype.

1) Next :-> The next() method returns an object with two properties done and value. You can also provide a parameter to the next method to send a value to the generator.
2) Throw :-> The throw() method resumes the execution of a generator by throwing an error into it and returns an object with two properties done and value

3) Return :-> A return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true ). If a value is returned, it will be set as the value property of the object returned by the generator.

Each Generator has 3 level prototype chaining as in the above image, but at the end, it is the type of ‘object’ In short, In Javascript, everything is the object.

Example 2

In the given example you can see, we can assign any value to yield which we want back while we are calling the next method. here we have passed a simple array and also passed * with an array, both work differently if we give array with * it consider like bellow. 
yield *[10,20,30] =
yield 10, yield 20, yield 30

Example 3

In the given example, we are passing value through the next method and as a result, we are getting all the values that we have passed like we can use generator function in many more ways.

Why use Iterator:
In short, we can say, It is used for maintaining the sequence of execution like we do a similar thing using callback or promise or async-await. Iterator allows us to execute the lines one by one using the ‘next()’ method.

let’s see the callback, Promise and Async await

Callback Function
If we are passing a function to another function and executing it inside that other function, for this scenario we call it a callback function. 

Why do we need Callback Functions?

JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has been completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened or some task is completed. Let’s see how…

In the above example, we want to start console output and then finish console output, so we are passing one function as a parameter to another function and executing it in that function. 
Promise and async-await are also used for the same purpose for performing operations one after another.

Generator and Async-await — Comparison

A generator function is executed yield by yield i.e one yield-expression at a time by its iterator (the next method) whereas async-await, they are executed sequential await by await. Async/await makes it easier to implement a particular use case of Generators.

Let’s see the custom Iterator example

function makeRangeIterator(start = 0, end = Infinity, step = 1) {
    let nextIndex = start;
    let iterationCount = 0;
    const rangeIterator = {
       next: function() {
           let result;
           if (nextIndex < end) {
               result = { value: nextIndex, done: false }
               nextIndex += step;
               return result;
           return { value: iterationCount, done: true }
    return rangeIterator;

Initializing iterator

const it = makeRangeIterator(1, 10, 2);
let result =;
while (!result.done) {
 console.log(result.value); // 1 3 5 7 9
 result =;
console.log("Iterated over sequence of size: ", result.value); // [5 numbers returned, that took interval in between: 0 to 10]

likewise, we have understood the concept of Generator function, I hope this article helped you to enhance your knowledge about the generator function.

Some of the references for a better understanding:
* we use generator function in react sagas
* Tutorial


In this article, we have dived deep into how the aptly named ‘Generator’ function in javascript vastly simplifies the otherwise tedious proces of wrtiting iterators. It allows you to pause the function while it is running, exit it and then at a later stage, re-enter it and resume from where it had paused.

One thought on “All About the ‘Generator’ Function in Javascript

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.