JavaScript | Generator.prototype.next() Method

The Generator.prototype.next() method is an inbuilt method in JavaScript which is used to return an object with two properties done and value.

Syntax:

gen.next( value );

Parameters: This function accepts 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:

  1. done: It has the value
    • true – for the iterator which past the end of the iterated sequence.
    • false – for the iterator which are able to produce the next value in the sequence.
  2. value: It contains any JavaScript value which is returned by the iterator.

Below examples illustrate the Generator.prototype.next() method in JavaScript:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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());  

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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);              
    
document.writeln(geek.next().value+"<br>");      
document.writeln(geek.next().value+"<br>");    
document.writeln(geek.next().value+"<br>");    
document.writeln(geek.next().value+"<br>");

chevron_right


Output:

geeks1,geeks2,geeks3,geeks4
geeks5,geeks6,geeks7,geeks8
geeks9,geeks10,geeks11
undefined

Supported Browsers: The browsers supported by Generator.prototype.next() method are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.