JavaScript Generator next() Method

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 "zambiatek";
    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: "zambiatek", 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 = [
    'zambiatek1', 'zambiatek2', 'zambiatek3',
    'zambiatek4', 'zambiatek5', 'zambiatek6',
    'zambiatek7', 'zambiatek8', 'zambiatek9',
    'zambiatek10', 'zambiatek11'
];
  
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:

zambiatek1,zambiatek2,zambiatek3,zambiatek4
zambiatek5,zambiatek6,zambiatek7,zambiatek8
zambiatek9,zambiatek10,zambiatek11
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.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button