yield & Use Cases

The yield keyword is used inside generator functions to pause and resume execution, producing a sequence of values on demand.

Illustration of yield & Use Cases
Illustration of yield & Use Cases

💡 What is yield?

yield pauses a generator function and returns a value to the caller, resuming from that point when next invoked.

Basic Syntax

A generator function uses function* syntax and yield to output values:

📌 Deep Dive: Simple Generator

JAVASCRIPT
function* count() {
  yield 1;
  yield 2;
  yield 3;
}

const iterator = count();

console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3
Output
1
2
3

Use Cases of yield

  • Lazy Iteration: Generate values on demand rather than all at once, saving memory.
  • Asynchronous Programming: Pausing execution at yield can simplify async flows (e.g., with libraries before async/await).
  • Implementing Iterators: Easily create custom iterable objects by yielding sequence values.
  • State Machines: Manage complex state transitions by pausing and resuming at each state.
  • Infinite Sequences: Generate potentially infinite data streams without blocking or heavy memory use.

💡 Key Insight

Generators with yield allow stepping through data or logic one piece at a time, rather than all at once.

Example: Infinite Sequence Generator

📌 Deep Dive: Infinite Numbers

JAVASCRIPT
function* infiniteNumbers() {
  let num = 1;
  while (true) {
    yield num++;
  }
}

const gen = infiniteNumbers();

console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
// and so on...
Output
1
2
3

Comparison: yield vs return

yield vs return
yieldreturn
Pauses function, produces a value, and can resume laterExits function immediately, producing a single value
Used inside generator functions (function*)Used in any function
Allows producing multiple values over timeProduces exactly one value
Enables lazy iterationDoes not support iteration

⚠️ Important

Generators must be iterated via their iterator (.next()) or with for...of loops to access yield values.

Common Pattern: Using yield with for...of

📌 Deep Dive: Iterating Generator

JAVASCRIPT
function* colors() {
  yield 'red';
  yield 'green';
  yield 'blue';
}

for (const color of colors()) {
  console.log(color);
}
Output
red
green
blue

💡 Summary

yield is a powerful tool to create generators that produce values on demand, enabling efficient iteration, complex state management, and lazy evaluation.