Explain Different kinds of Generators in JavaScript


As we know JavaScript is a lightweight programming language in which generators were introduced in ECMAScript 2015. A generator is a process that has many output values and may be stopped and started. In JavaScript, a generator is made up of a generator function that produces an iterable Generator object.

In this article, we are going to discuss the generators in JavaScript and also the different types of generators in JavaScript with syntax and examples in detail.

Introduction to Generators in JavaScript

The generator's function is as same as the regular function but there is a bit of difference in that the generator function can be resumed and paused. In JavaScript generally, functions are not stope when once they are invoked. Usually, the concept of generators is seen in asynchronous programming.

Syntax of Generator function in JavaScript

Now we will be going to discuss the syntax of the generator function in the JavaScript and also compare it with the regular function.

The function * syntax is used to build generator functions, and the yield keyword is used to pause them.

function * genFunc() {
   yield 'Hello';
   yield 'World';
}
const g = genFunc(); // g is a generator
g.next(); // { value: 'Hello', done: false }
g.next(); // { value: 'World', done: false }
g.next(); // { value: undefined, done: true }
…

When a generator function is first called, none of its code is run, Instead, a generator object is returned. Values are consumed by invoking the next() method of the generator, which runs code until it comes across the yield keyword, at which point it pauses and waits until the next() is invoked once more.

In the above code, after our final statement, continually calling g.next() will only produce the same return object: {value: undefined, done: true} because we have not defined anything after the ‘world’ in our genFunc() function.

The yield keyword pauses the generator function's execution and gives the caller of the generator the value of the expression that follows it. It is comparable to the generator-based version of the return keyword. It can only be directly called from the generator function that contains yield.

Comparison with regular function

function regFunc() {
   console.log("Hello World");
}
// Hello World

In the regular function, we do not use the ‘*’ function as you can see above example it also does not use the yield function. As we discussed above that the main difference between the regular function and the generator function is that the generator function can be stopped and paused. So by the above example, you can see that we don’t have the choice to stop it and directly print the whole statement together i.e “Hello world”.

As we have seen the basic of the generator functions, now let’s move to the different types of generator functions −

Normal Generator

In a normal generator, the generator works as the iterator that generates the next value after every next() method call is executed to generate a function. Let’s see an example, where we are going to yield the numbers one by one until the list ends.

function* generator_function(){
   for(var cur = 0 ; cur<7; cur++){
      yield cur;
   }
}
var object_generator = generator_function();
console.log(object_generator.next().value);
console.log(object_generator.next().value);
console.log(object_generator.next().value);
console.log(object_generator.next().value);
console.log(object_generator.next().value);
console.log(object_generator.next().value);
console.log(object_generator.next().value);

In the above code, we have created a normal general function with the yield keyword present in it and used the next() function to call it several times.

Generator with Parameters

The generator with parameters is a bit different from the normal generators and this time we have to pass a parameter with the next() function to send it to the generator function. Also every time we pass a parameter it kind of stores after the yield keyword, not before that, we will understand this concept in the upcoming example −

function* generator_function(){
   console.log("start of the function")
   temp = yield;
   console.log("This is the first value passed: " + temp)
   temp = yield;
   console.log("This is the second value passed: " + temp)
}
var object_generator = generator_function();
object_generator.next("This is not the first ");
object_generator.next("this is first");
object_generator.next("this is second");
object_generator.next();

In the above code, we have defined the generator function, and this time we are passing the parameters to it. When we first called the object the given parameter is not printed because that is for sending before the ‘yield’ keyword, then after the sent values are stored in the variables and printed and after the second printed value there will nothing happens because there is no yield present.

Generator with Object Property

Generators can be used as objects and when we will call them they will simply return the value that is assigned to them and that can be printed. To understand this concept let’s see an example.

function* generator_function(){
   yield "First value"
   yield "Second value"
   yield "Third value"
}
var object_generator = generator_function();
console.log(object_generator.next().value);
console.log(object_generator.next().value);
console.log(object_generator.next().value);

In the above code, first, we have defined three yield expressions with a string present after them and when we have called the generator then the string present after them will be returned.

There are other types of generators also present like with return type and some contain another generator inside of them, etc.

Conclusion

In the article, we have learned that the generator's function is as same as the regular function but there is a bit of difference in that the generator function can be resumed and paused. In JavaScript generally, functions are not stope when once they are invoked. Usually, the concept of generators is seen in asynchronous programming. There are various types of generators like a normal generator, with parameters, objects like property, generator contains another generator, etc.

Updated on: 17-Mar-2023

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements