Advertisement
Intermediate JavaScript, Iterators & Generators

How do you delegate from one generator to another using yield*?

Short answer

yield* fully delegates iteration to another iterable (including another generator), yielding each of its values in turn as if they were yielded directly by the outer generator — useful for composing generators without manually re-yielding each value.

Save JavaScript mock interview
Advertisement
AModel answer
yield* fully delegates iteration to another iterable (including another generator), yielding each of its values in turn as if they were yielded directly by the outer generator — useful for composing generators without manually re-yielding each value.
function* inner() { yield 'a'; yield 'b'; }
function* outer() {
  yield 1;
  yield* inner(); // delegates to inner()
  yield 2;
}
[...outer()]; // [1, 'a', 'b', 2]
Real-world example
Composing a large generator out of smaller, reusable generator building blocks.
Likely follow-ups
  • Can yield* delegate to any iterable, or only to other generators?
Related topics