Tutorialspoint.dev

JavaScript | Generator

Like Python Generators, JavaScript also supports Generator functions and Generator Objects.

Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. The yield statement suspends function’s execution and sends a value back to caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run.

Syntax :

// An example generator function
function* gen(){
     yeild 1;
     yeild 2;
     ...
     ...
}

Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop (as shown in the above program)
The Generator object is returned by a generating function and it conforms to both the iterable protocol and the iterator protocol.

<script>
// Generate Function generates three 
// different numbers in three calls
function * fun()
{
    yield 10;
    yield 20;
    yield 30;    
}
  
// Calling the Generate Function
var gen = fun();
document.write(gen.next().value);
document.write("<br>");
document.write(gen.next().value);
document.write("<br>");
document.write(gen.next().value);
</script>                    

Below is an example code to print infinite series of natural numbers using a simple generator.

<script>// Generate Function generates an 
// infinite series of Natural Numbers 
function * nextNatural()
{
    var naturalNumber = 1;
  
    // Infinite Generation
    while (true) {
        yield naturalNumber++;
    }
}
  
// Calling the Generate Function
var gen = nextNatural();
  
// Loop to print the first
// 10 Generated number
for (var i = 0; i < 10; i++) {
  
    // Generating Next Number
    document.write(gen.next().value);
  
    // New Line
    document.write("<br>");
}
</script>

/div>

Output

1
2
3
4
5
6
7
8
9
10


This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter