1

Here is my sample code:

function *g() {
  while (true) {
    console.log(yield)
  }
}

var gen = g();
gen.next(3); // {value: undefined, done:false}
gen.next(3); // 3 {value: undefined, done:false}
gen.next(3); // 3 {value: undefined, done:false}

Why the first argument passed to the first next() function doesn't work ? And why the value property's value is undefined, shouldn't it be the argument value passed in ?

nem035
  • 34,790
  • 6
  • 87
  • 99
hh54188
  • 14,887
  • 32
  • 113
  • 184

1 Answers1

2

Here's what happens in a generator.

The first call initializes the generator (and returns an iterator), doesn't run any internal code.

From then on, every call to .next(value) on the iterator passes the value to be returned from the currently paused yield and continues execution to the next yield (or end of the function), returning the yield-ed (or returned) value.

Now, what is the currently paused yield on the first .next call? There isn't one, we started execution from the top of the function instead.

Hence the first value is undefined no matter what you pass into the first next call (it's just ignored).

As far as the yield-ed value being undefined, you get what you yield.

function *g() {
  yield;     // yields undefined
  yield 3;
  yield 'a';
}

for (const v of g()) {
  console.log(v);
}
nem035
  • 34,790
  • 6
  • 87
  • 99
  • 1
    TIL `for (const v of g())`, I didn't realize you could do that! In hindsight, it's rather the point. – msanford Aug 07 '17 at 18:11