The Wayback Machine - https://web.archive.org/web/20230512160051/https://www.geeksforgeeks.org/javascript-generator-reference/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

JavaScript Generator Reference

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

JavaScript Generator is used to allow us to define an iterative algorithm by writing a single function whose execution is not continuous.

Generator Constructor & Generator Objects

  • Generator() Construcotr: A generator constructor 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

The complete list of JavaScript Generators are listed below.

JavaScript Generator Constructor: In JavaScript, a constructor gets called when an object is created using the new keyword.

ConstructorDescription
GeneratorIt is not available globally. Instances of Generator returned from generator functions.

JavaScript Generator Properties: A JavaScript property is a member of an object that associates a key with a value.

  • Instance Property: An instance property is a property that has a new copy for every new instance of the class.

Instance PropertiesDescription
constructorReturn the generator constructor function for the object.

JavaScript Generator Methods: JavaScript methods are actions that can be performed on objects.

  • Instance Method: If the method is called on an instance of a generator then it is called an instance method.

Instance MethodsDescription
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
Last Updated : 10 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials