How does processes its parameter?

The documentation says that “You can also provide a parameter to the next method to send a value to the generator.” Where does it sends it to?

For example, take these 3 generators:

function* one() {
  while(true) {
    var value = yield null;
var g1 = one();;; //yields null

function* two() {
  var i = 0;
  while (true) {
    i += yield i;
var g2 = two();; // yields 1000

function* three(){
  var index = 0;
  while (true)
    yield index++;

 g3 = three();;; // yields 1

In generators 3 and 1, the argument passed has no effect on next. Why is that? How does generator 2 calculates its return value? Why it is affected by the given argument?


The key to understanding this is knowing how the next function retrieves the argument passed to next(), which is as the return value of the yield operator:

[rv] = yield [expression];

Independently of the value of [expression], yield will assign to rv the value passed to next().

But, here comes the tricky part: yield will only assign the value passed to next() when resuming execution from a previous iteration. As a consequence, on the first iteration, yield does not assign anything to rv.

For example, if I have this generator:

function* gen() {
  // On the first iteration, yield does not return anything.
  //because it returns something ONLY when execution is resumed
  returnedFromYield = yield 'foo'; 
  yield returnedFromYield; 

returnedFromYield is undefined on the first iteration. When execution is resumed on the second iteration, yield assigns the passed value to the returnedFromYield variable, which is then returned:; // 'foo'; // 2

Let’s review another example:

function* gen() {
  yield yield yield 5;

On the first iteration, (, yield will return 5, on the second iteration, ( yield is going to pass 10 to the second yield. That is, yield yield yield 5; on the second iteration is equivalent to yield yield 10;, and, on the third iteration, it’s equivalent to yield valuePassedToNext.

Source : Link , Question Author : Federico , Answer Author : Federico

Leave a Comment