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.
Syntax:
gen.next( value );
Parameters: This function accepts a single parameter as mentioned above and described below:
- value: This parameter holds the value to be sent to the generator.
Return value: This method returns an object containing two properties:
- done: It has the value
- true – for the iterator which is past the end of the iterated sequence.
- false – for the iterator which is able to produce the next value in the sequence.
- value: It contains any JavaScript value which is returned by the iterator.
The below examples illustrate the Generator.prototype.next() method in JavaScript:
Example 1: In this example, we will create a generator and then apply the Generator.prototype.next() method and see the output.
javascript
<script> function * GFG() { yield "GeeksforGeeks" ; yield "JavaScript" ; yield "Generator.prototype.next()" ; } const geek = GFG(); console.log(geek.next()); console.log(geek.next()); console.log(geek.next()); console.log(geek.next()); </script> |
Output:
Object { value: "GeeksforGeeks", done: false } Object { value: "JavaScript", done: false } Object { value: "Generator.prototype.next()", done: false } Object { value: undefined, done: true }
Example 2: In this example, we will create a generator and then apply the Generator.prototype.next() method and see the output.
javascript
<script> function * GFG(len, list) { let result = []; let val = 0; while (val < list.length) { result = []; let i = val while (i < val + len) { if (list[i]) { result.push(list[i]); } i+=1 } yield result; val += len; } } list = [ 'geeks1' , 'geeks2' , 'geeks3' , 'geeks4' , 'geeks5' , 'geeks6' , 'geeks7' , 'geeks8' , 'geeks9' , 'geeks10' , 'geeks11' ]; var geek = GFG(4, list); console.log(geek.next().value); console.log(geek.next().value); console.log(geek.next().value); console.log(geek.next().value); </script> |
Output:
geeks1,geeks2,geeks3,geeks4 geeks5,geeks6,geeks7,geeks8 geeks9,geeks10,geeks11 undefined
We have a complete list of Javascript Generator function methods, to check those please go through the Javascript Generator Complete Reference article.
Supported Browsers: The browsers supported by Generator.prototype.next() method are listed below:
- Google Chrome
- Firefox
- Opera
- Safari
- Edge
Please Login to comment...