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).
1 Answer 1
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.
yield*is an expression. The only other differences are thatyield*is quicker to write, and I would guess it has been optimized somewhat.yield ...is an expression too.for ... ofis a statement, so you can dovar x = yield* ..., but notvar x = for ....