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

When to Use yield vs yield*

Distinguish use cases for direct yielding versus delegation.

When to Use yield vs yield*

You'll learn how to decide when to yield values directly versus delegating to another iterable.

The Core Difference

Think of yield as personally handing out individual items one by one, while yield* is like saying "this other person has a whole basket of items — let them handle distribution."

Use yield when you want to:

  • Produce single values directly from your generator
  • Maintain full control over what gets yielded
  • Transform or compute values before yielding them

Use yield* when you want to:

  • Delegate iteration to another iterable (generator, array, string, etc.)
  • Avoid manual loops to yield all values from a collection
  • Flatten nested structures or compose generators

Practical Decision Guide

If you're producing individual values or need to process each one, stick with yield:

function* evenNumbers(max) {
  for (let i = 0; i <= max; i += 2) {
    yield i;  // Direct control over each value
  }
}

If you're passing through an entire iterable without modification, use yield*:

function* numbers(max) {
  yield* [1, 2, 3];  // Delegate to the array
  yield* evenNumbers(max);  // Delegate to another generator
}

Without yield*, you'd have to write a loop with yield for each element — verbose and less clear.

Key Takeaway: Use yield when you're producing or transforming individual values; use yield* when you're delegating iteration to another iterable without modification.