Explain different kinds of generators in JavaScript
Last Updated :
12 Dec, 2022
Generators are the function whose execution can be paused and resumed as per the requirement of the programmer. We use the yield keyword in this function to stop the execution of code. Generators are very useful in asynchronous programming. Generators combine with different features of programming language and make itself vary useful for programmer for use it for effective programming.Â
Generators can be created using the generator function expression and Generator function constructor:
Function expression:
function* FUNCTION_NAME( argu1[, argu2[,...argu3]]]) {
// Generator body
}
Generator function constructor:
var generator_constructor =
Object.getPrototypeOf( function*(){} ).constructor
var FUNCTION_NAME = generator_constructor()
Because Generators are vary useful. Let's talk about different kinds of generators in javascript:Â
Normal Generator: It is the generator kind in which a generator like an iterator generates the next value after the execution of each next() method to the generator function. Â Here in this kind, we will yield numbers in a continuous manner till the last yield keyword.Â
JavaScript
function* generator(){
for(var i = 0 ; i<5; i++){
yield i;
}
}
var first_gen = generator();
console.log(first_gen.next().value);
console.log(first_gen.next().value);
console.log(first_gen.next().value);
console.log(first_gen.next().value);
console.log(first_gen.next().value);
Output:
0
1
2
3
4
Generator with Parameters: In this Generator, we pass the parameter to the generator's next method and it replaces this parameter with the last yield keyword which is before pausing the execution of the function. Here the first next method of generators function's parameter will not replace with any yield keyword because no yield keywords are before the first pause of function. In the same manner seconds, call of next method with parameter is replaced with the first yield keyword and the third next method parameter is replaced with second yield keyword.
JavaScript
function* generator(){
para1 = yield ;
console.log(para1);
para2 = yield ;
console.log(para2)
}
var first_gen = generator();
first_gen.next("this is not going to assign any one");
first_gen.next("I am first");
first_gen.next("I am second")
Output:
I am first
I am second
Generator with Object property: In this kind of Generator, Generator is defined as the property of the Object. We can create a generator instance and then execute the next method for further execution of the generator. In this case, the generator is as same as a normal generator but it is a property of an Object.Â
JavaScript
var temp = {
*generator(){
yield "1 yield";
yield "2 yield";
}
}
var gen = temp.generator();
console.log(gen.next().value);
console.log(gen.next().value);
Output:
1 yield
2 yield
Generator with Another Generator: In this kind of Generator we have a generator that contains a Yield with another Generator inside its function body. When execution encounters yield with another generator it finishes execution of that generator and then continues with the primary generator.Â
JavaScript
function* generator1(){
yield "this is first Generator";
}
function* generator2(){
yield* generator1();
yield "this is second Generator";
}
var gen = generator2();
console.log(gen.next().value);
console.log(gen.next().value);
Output:
this is first Generator
this is second Generator
Generator with Return Keyword: In this kind of generator, the function Body contains a return Keyword. Here when the generator function encounters the return keyword it stops and exits from the execution of the function and returns the value generator object. After the return keyword will never be executed in the execution of our program.Â
JavaScript
function* Return_generator(){
yield "First";
return "Second";
yield "Infinite";
}
var gen = Return_generator();
console.log(gen.next().value);
console.log(gen.next().value);
Output:
First
Second
Generator created as Object method: We can create Generator as a method of Object and can use them as per requirement. In this kind, as we create a normal function to Object same we create Generator function of Object. We can use the Generator function with the instance of Object. In this case, Generator is available as the method of Object.Â
JavaScript
class temp{
*generator(){
yield "Generator with object method ";
yield "Second flow of Generator";
}
}
var temp2 = new temp()
var gen = temp2.generator();
console.log(gen.next().value);
console.log(gen.next().value);
Output:
Generator with object method
Second flow of Generator
Similar Reads
Explain the Different Function States in JavaScript
In JavaScript, we can create functions in many different ways according to the need for the specific operation. For example, sometimes we need asynchronous functions or synchronous functions. Â In this article, we will discuss the difference between the function Person( ) { }, let person = Person ( )
3 min read
JavaScript Function Generator
A generator function is a special type of function that can pause its execution at any point and resume later. They are defined using the function* syntax and use the yield keyword to pause execution and return a value.Syntaxfunction* generatorFunction() { // Code that can yield multiple values }Jav
3 min read
What to understand the Generator function in JavaScript ?
Generators generate value on the fly which means whenever there is a need for that value then only it will be generated. It means the value is generated but not stored in memory so it takes less time to execute. It uses asterick (*) symbol after the keyword function i.e. function* to tell javaScript
4 min read
Explain the different variants of for loop in TypeScript
Loops are used to execute a specific block of code a specific number of times. There are 2 types of loops in TypeScript which are Definite Loop (for), and Indefinite Loops (while, do..while) In TypeScript, we have basically 3 kinds of for loops. forfor .. offor .. in for loop: The for loop is used t
4 min read
Difference between Generators and Iterators in JavaScript
GeneratorsThe Generators are a special type of function in JavaScript that can be paused and resumed during their execution. They are defined using the asterisk (*) after the function keyword. The Generators use the yield keyword to yield control back to the caller while preserving their execution c
2 min read
How to generate all combinations of a string in JavaScript ?
We are going to see if we can generate all the possible combinations of a given string using JavaScript methods or concepts. You are given a string, containing different characters, you need to generate all combinations of a string by selecting a character at once and then re-arranging that characte
4 min read
Explain the concept of generators in Redux Saga.
Redux Saga is like a wise and powerful wizard for managing complex tasks in your React and Redux app. It specializes in handling asynchronous operations, like fetching data or dealing with side effects, making your code more organized and your app's behavior smoother. Think of it as a magical assist
2 min read
Difference Between for...in and Object.keys() in JavaScript
The for...in and Object.keys() in JavaScript are used to iterate over the properties of an object. While they might seem similar at first glance they have distinct usage, behavior, and characteristics. This article will explore these differences in detail.These are the following topics that we are g
3 min read
Difference between function expression vs declaration in JavaScript
Function Declaration: A Function Declaration( or a Function Statement) defines a function with the specified parameters without requiring a variable assignment. They exist on their own, i.e, they are standalone constructs and cannot be nested within a non-function block. A function is declared using
1 min read
Interesting Code Snippets in JavaScript
JavaScript is a flexible and powerful programming language that can solve problems in clever and simple ways. Here are some fun JavaScript code snippets that highlight its features and quirks. Whether you're a beginner or an experienced developer, these examples will spark your interest.1. Flattenin
5 min read