Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript Generator Complete Reference

Improve Article
Save Article
  • Last Updated : 09 Jan, 2023
Improve Article
Save Article

JavaScript Generator and Generator Objects:

  • Generator-Function: A generator-function is defined as a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. 
  • 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 of” loop.

Syntax : 

// An example of the generator function
function* gen(){
    yield 1;
    yield 2;
    ...
    ...
}

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

Javascript




<script>
    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
       console.log(gen.next().value)
    }
</script>

Output:

1    
2
3
4
5
6
7
8
9
10

JavaScript Generator Instance methods: The complete list of JavaScript Generators are listed below.

Methods

Description

next()Return an object with two properties done and value.
return()Return the given value and finishes the generator.
throw() The execution of a generator by throwing an error into it.
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!