Search code examples
javascriptgenerator

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


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 to till the first yield and then returns 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");