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
JavaScript Generator Instance methods: The complete list of JavaScript Generators are listed below.
Please Login to comment...