Open In App

JavaScript Generator Reference

Improve
Improve
Like Article
Like
Save
Share
Report

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() Constructor: 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




function* nextNatural() {
    let naturalNumber = 1;
  
    // Infinite Generation
    while (true) {
        yield naturalNumber++;
    }
}
  
// Calling the Generate Function
let gen = nextNatural();
  
// Loop to print the first
// 10 Generated number
for (let i = 0; i < 10; i++) {
  
    // Generating Next Number
    console.log(gen.next().value)
}


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.

Constructor Description Example
Generator It is not available globally. Instances of Generator returned from generator functions.
Try

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 Properties Description Example
constructor Return the generator constructor function for the object.
Try

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 Methods Description Example
next() Return an object with two properties done and value.
Try

return() Return the given value and finishes the generator.
Try

throw() The execution of a generator by throwing an error into it.
Try


Last Updated : 25 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads