0

As the question states, does it ever make sense to pass a value to the first iterator.next() call or will it always be ignored? As an example:

function* foo(x) {
  var y = 2 * (yield(x + 1));
  var z = yield(y / 3);
  return (x + y + z);
}

var it = foo(5);

// note: not sending anything into `next()` here
console.log(it.next()); // { value:6, done:false }
console.log(it.next(12)); // { value:8, done:false }
console.log(it.next(13)); // { value:42, done:true }

Notice there is not a value being passed to the first next(). However, in the article I'm trying to learn from, it goes on to say:

But if we did pass in a value to that first next(..) call, nothing bad would happen. It would just be a tossed-away value

Okay. That makes sense. But now I'm curious to know if there is a use case (or if it's even possible to utilize) where passing in a value has a benefit.

Article: https://davidwalsh.name/es6-generators

RobG
  • 142,382
  • 31
  • 172
  • 209
adam-beck
  • 5,659
  • 5
  • 20
  • 34
  • The argument passed in the *next* call replaces the value returned by the previous *yield* expression. Since on the first call there is no previous *yield*, there's nothing to replace so there doesn't seem to be any use case for including it. – RobG Nov 06 '17 at 05:02

1 Answers1

0

Will it always be ignored?

Yes.

Is a use case where passing in a value has a benefit?

When it simplifies the rest of your code. In your example, that could be using a loop instead of writing it out:

const it = foo(5);
for (let i=11; i<=13; i++)
    console.log(it.next(i));

Now we're passing 11 into the first call to .next even if there's no use for the value anywhere.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375