vikrant
vikrant

Reputation: 2277

How does calling the `next()` method with a value replaces the previous `yield` expression in javascript generators?

This is from MDN:

gen.next(value)
The value will be assigned as a result of a yield expression. For example, in variable = yield expression, the value passed to the .next() function will be assigned to variable.

Also, this is from Medium article:

The second next(10) call, replaces the entire first yield expression with 10

So my question is, how is the next(value) replacing the "previous" yield expression? how is it working behind the scenes. I have read about iterators but i can't understand how is next() working in this case.

Upvotes: 1

Views: 363

Answers (1)

Barmar
Barmar

Reputation: 781058

When a generator executes a yield statement

variable = yield value;

it sends value to the most recent caller of next(). Then it waits for another call to next(). The value passed as an argument to that call is used as the value of this yield expression, which is assigned to variable.

Then it continues with the rest of the code in the generator. The next use of yield repeats the above process.

It's this way because JavaScript combines sending output and receiving input into a single operation. The first input to the generator comes through the parameter list, all the future inputs come from yield, which gets the values from the corresponding next() calls. It has to send to the last yield because of this order of operations.

Upvotes: 3

Related Questions