Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What happens to argument value of first .next() in generator function*

Consider this generator function.

Why is the argument of the first call to .next() essentially lost? It will yield and log each of the letter strings but skips "A". Can someone offer an explanation. Please advise on a way that I can access each argument each argument of the .next() method and store it in an array within the generator function?

function* gen(arg) {
  let argumentsPassedIn = [];
  while (true) {
    console.log(argumentsPassedIn);
    arg = yield arg;
    argumentsPassedIn.push(arg);
  }

}


const g = gen();
g.next("A"); // ??
g.next("B");
g.next("C");
g.next("D");
g.next("E");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As per the docs

The first call of next executes from the start of the function until the first yield statement

So when you call the first next, it just calls the generator function from start, where arg will be empty and from next call it works normal.

To make you code work, you should try like this.

function* gen(arg) {
  let argumentsPassedIn = [];
  while (true) {
    console.log(argumentsPassedIn);
    arg = yield arg;
    argumentsPassedIn.push(arg);
  }

}


const g = gen();
g.next()
g.next("A"); // ??
g.next("B");
g.next("C");
g.next("D");
g.next("E");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading