Elliot E
Elliot E

Reputation: 452

Difference between yield * and yielding in a for..of loop?

Given the following two pieces of code:

function * gen(g) {
  for (const value of g) {
    yield value;
  }
}

and

function * gen(g) {
  yield * g;
}

is there any difference in the behavior? As far as I can tell these are behaviorally identical. I'm having trouble seeing the value of the yield * syntax. It's more limiting than just iterating over the iterable in a for..of loop, and less obvious in what it does when reading it (in my opinion).

Upvotes: 0

Views: 228

Answers (1)

tmcw
tmcw

Reputation: 11882

Here's the ExploringJS explanation of the difference, which is very exhaustive. The answer is typically, yes, they're equivalent, but there are some small differences. The most notable difference is that return values are forwarded by yield * but not by iterating and yielding.

Here's an example. The difference is minor.

Upvotes: 1

Related Questions