What to understand the Generator function in JavaScript ?
Last Updated :
17 Apr, 2023
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 it is a generator function. The generator function returns the object.
Use cases:
- It uses in infinite loop and does not stop computer or freeze your program.
- It uses as iterator.
It has special type of return keyword i.e. Yield. The purpose yield is to run some code then return value, run some more code and return value like that.
Example: It is useful when it’s expensive to do each step of the yield like when you are hitting an API endpoint on each yield and don’t know how many results users will want, so in that case, you can delay those API calls until they are actually needed.
Generators have two properties:
- Value property
- Done property
Syntax:
Javascript
function * Generator(){
yield 1
yield 2
yield 3
}
const gen = Generator();
|
It uses three type of function mainly:
- Next function
- Return function
- Throw function
So, Here we discuss next function through example.
Example 1: This example shows the use of generators in Javascript.
Javascript
function * Generator() {
yield 1;
yield 2;
yield 3;
}
const gen = Generator();
console.log(gen.next());
console.log(gen.next());
|
Output
{ value: 1, done: false }
{ value: 2, done: false }
Example 2: This example shows the use of generators in Javascript.
Javascript
function * Generator() {
console.log( "before 1" );
yield 1;
console.log( "after 1" );
console.log( "before 2" );
yield 2;
console.log( "after 2" );
}
const gen = Generator();
|
Output: It does not print anything as when the generator calls the first time it creates an object that has the next property because the next property allows to singly execute all the code inside the generator.
Example 3: This example shows the use of generators in Javascript.
Javascript
function * Generator() {
let i = 0;
while (i < 5) {
yield i;
i++;
}
}
const gen = Generator();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
|
Output: Here while loop runs only 5 times, and after that loop terminate that’s why here 5th index value is undefined and done property is true as yield return till 5 value after that generator can’t generate value.
{ value: 0, done: false }
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: 4, done: false }
{ value: undefined, done: true }
Example 4: This example shows the use of generators in Javascript.
Javascript
function * Generator() {
let i = 0;
while (i < 2) {
yield i++;
}
}
const gen = Generator();
console.log(gen.next().value);
console.log(gen.next().value);
|
Output:
0
1
Example 5: This example shows the use of generators in Javascript. Here generator use as iterator for array.
Javascript
function * Generator(array) {
for (let i = 0; i < array.length; i++) {
yield array[i];
}
}
const gen = Generator([1, 3, 5]);
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
|
Output
{ value: 1, done: false }
{ value: 3, done: false }
{ value: 5, done: false }
{ value: undefined, done: true }
Example 6: This example shows the use of generators in Javascript.
Javascript
function * Generator() {
let i = 0;
while (i < 4) {
yield i++;
}
}
const gen = Generator();
const gene = Generator();
console.log(gen.next());
console.log(gen.next());
console.log(gene.next());
console.log(gene.next());
|
Output
{ value: 0, done: false }
{ value: 1, done: false }
{ value: 0, done: false }
{ value: 1, done: false }
Each time when the generator function is called it creates a new instance for the separate object which has its own version of a function that can iteration through on its own.
Similar Reads
What is the send Function in Python Generators
Python generators are a powerful feature that allows for efficient iteration over potentially large datasets without the need to load everything into memory at once. A generator is a special type of iterable that uses the yield keyword to produce a sequence of values, one at a time. In addition to t
4 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 is the (function() { } )() construct in JavaScript?
If you've ever played around with JavaScript, you might have seen this expression. It's like a strange set of symbols, but it has a special name that is an immediately invoked function expression, or IIFE. In this article, we will understand each element of the expression as well as the functionalit
3 min read
How to write a function in JavaScript ?
JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
4 min read
How to Understand Recursion in JavaScript ?
Recursion is a process in which a function calls itself as a subroutine. This allows the function to be repeated several times, as it can call itself during its execution. Recursion is often used to solve problems that can be broken down into smaller, similar subproblems. Syntax:[GFGTABS] JavaScript
4 min read
JavaScript Generator next() Method
JavaScript Generator.prototype.next() method is an inbuilt method in JavaScript that is used to return an object with two properties done and value. Syntax: gen.next( value ); Parameters: This function accepts a single parameter as mentioned above and described below: value: This parameter holds the
2 min read
Explain different kinds of generators in JavaScript
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 l
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
Higher-Order Arrow Functions in JavaScript
Prerequisite: Arrow Functions A Higher-Order function is a function that receives a function as an argument otherwise returns the function as output. The higher-Order Arrow function implies using arrow functions (in ES6) along with Higher-Order functions. Needs of Higher Order Arrow Function: In a g
6 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