Course contentsShow
← JavaScript
Lesson 1113 of 2,72325. Iterators and GeneratorsFree lesson

The yield* Operator: Delegating to Another Iterable

Learn how yield* delegates iteration to another generator or iterable.

The yield* Operator: Delegating to Another Iterable

You'll learn how to use yield* to hand off iteration control from one generator to another iterable, making complex sequences simpler and more composable.

What Is yield*?

The yield* operator lets a generator delegate to another iterable (like an array, string, or another generator). Instead of manually looping and yielding each value one by one, yield* says "pause me, let this other iterable take over, and resume when it's done."

Think of it like a manager delegating a task: rather than doing every step yourself, you hand the entire job to someone else and wait for them to finish.

How It Works

When you use yield* followed by an iterable, the generator yields all values from that iterable automatically:

function* numbers() {
  yield 1;
  yield* [2, 3, 4]; // Delegates to the array
  yield 5;
}

const gen = numbers();
console.log([...gen]); // [1, 2, 3, 4, 5]

Without yield*, you'd need:

function* numbers() {
  yield 1;
  for (let num of [2, 3, 4]) {
    yield num; // Manual loop
  }
  yield 5;
}

Delegating to Other Generators

You can also delegate to another generator function:

function* inner() {
  yield 'A';
  yield 'B';
}

function* outer() {
  yield 1;
  yield* inner(); // Delegate to inner generator
  yield 2;
}

console.log([...outer()]); // [1, 'A', 'B', 2]

The outer generator pauses completely while the inner one runs.

Key Takeaway: yield* delegates iteration to another iterable, automatically yielding all its values without manual loops—perfect for composing generators or flattening sequences.