Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

JavaScript | Generator.prototype.next() Method

  • Last Updated : 16 Apr, 2020

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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:




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

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:




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

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :