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. Syntax function* generatorFunction() { // Code that can yield multiple values }[
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
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
Different ways of writing functions in JavaScript
A JavaScript function is a block of code designed to perform a specific task. Functions are only executed when they are called (or "invoked"). JavaScript provides different ways to define functions, each with its own syntax and use case. Below are the ways of writing functions in JavaScript: Table o
3 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
Difference Between Default & Named Exports in JavaScript
In JavaScript, exports allow you to share code between modules. There are two main types: default exports and named exports. Used to export functions, objects, or variables.Default exports allow importing with any name.Named exports require importing by the exact name.Named ExportsNamed exports let
4 min read
How to Generate a Random Number in JavaScript ?
To generate a random number in JavaScript, use the built-in methods that produce a floating-point number between 0 (inclusive) and 1 (exclusive). Below are the approaches to generate random numbers in JavaScript: Table of Content Using Math.random() methodUsing Math.floor() with Math.random()Using M
2 min read
Applications of Map in JavaScript
Javascript Map is a collection of elements where each element is stored as a Key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, and value pair in the same order as inserted. Syntax: new Map([it]); Pa
5 min read
How to Create a Link in JavaScript ?
In JavaScript, a link typically refers to creating HTML hyperlinks (<a> tags) dynamically using JavaScript. You can link using a document.createElement('a'), setting attributes like href and textContent, and then appending it to the document with appendChild(). Here are some common approaches
4 min read