0

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).

asked Apr 16, 2018 at 1:05
3
  • From what I see here, it looks like they're pretty much the same except that yield* is an expression. The only other differences are that yield* is quicker to write, and I would guess it has been optimized somewhat. Commented Apr 16, 2018 at 1:16
  • @Anonymous: yield ... is an expression too. Commented Apr 16, 2018 at 5:19
  • @FelixKing But for ... of is a statement, so you can do var x = yield* ..., but not var x = for .... Commented Apr 16, 2018 at 23:27

1 Answer 1

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.

answered Apr 16, 2018 at 1:30
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, exactly the kind of thing I was looking for.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.