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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>                    

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


Output

1
2
3
4
5
6
7
8
9
10


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.