JavaScript Generator Complete Reference
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
The complete list of JavaScript Generator are listed below:
Instance methods:
JavaScript Generator Instance methods | Description |
|---|---|
| JavaScript Generator.prototype.next() Method | The Generator.prototype.next() method is an inbuilt method in JavaScript that is used to return an object with two properties done and value. |
| JavaScript Generator.prototype.return() Method | The Generator.prototype.return() method is an inbuilt method in JavaScript which is used to return the given value and finishes the generator. |
| JavaScript Generator.prototype.throw() Method | The Generator.prototype.throw() method is an inbuilt method in JavaScript that is used to resume the execution of a generator by throwing an error into it. |






Please Login to comment...