JavaScript 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
function * GFG() { yield "neveropen" ; 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()); |
Output:
Object { value: "neveropen", 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
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 = [ 'neveropen1' , 'neveropen2' , 'neveropen3' , 'neveropen4' , 'neveropen5' , 'neveropen6' , 'neveropen7' , 'neveropen8' , 'neveropen9' , 'neveropen10' , 'neveropen11' ]; let geek = GFG(4, list); console.log(geek.next().value); console.log(geek.next().value); console.log(geek.next().value); console.log(geek.next().value); |
Output:
neveropen1,neveropen2,neveropen3,neveropen4 neveropen5,neveropen6,neveropen7,neveropen8 neveropen9,neveropen10,neveropen11 undefined
Supported Browsers: The browsers supported by Generator.prototype.next() method are listed below:
- Google Chrome
- Firefox
- Opera
- Safari
- Edge
We have a complete list of Javascript Generator methods, to check those please go through the Javascript Generator Reference article.