Open In App

JavaScript Generator Reference

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



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.






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

Article Tags :