Skip to content
Concept 66 // Module 07: Collections, Iteration & Modules

Generators: function* & yield

Module 07: Collections, Iteration & Modules•Concept 66 of 100• 5 min read

Generators: function* & yield

**Generators** are functions that can be paused and resumed. They return an **Iterator** and allow you to produce a sequence of values over time, only calculating the next value when requested.

The Core Concept

Syntax Reference
// 1. Generator Declaration (*)
function* generatorFunc() {
  yield 1;
  yield 2;
  return 3;
}

// 2. Consumption
const gen = generatorFunc();
gen.next(); // { value: 1, done: false }
gen.next(); // { value: 2, done: false }
gen.next(); // { value: 3, done: true }

Live Interactive Studio

Generators can contain infinite loops without crashing! They simply pause at the `yield` statement and wait for the next `.next()` call.
JavaScript Editor
Loading...
Console Output
Waiting for output...

Key Code Patterns in Action

01

Infinite ID Generator

// 1. Infinite ID Generator
function* idMaker() {
  let id = 1;
  while (true) {
    yield id++;
  }
}

const ids = idMaker();
console.log(ids.next().value); // 1
console.log(ids.next().value); // 2
Generators can contain infinite loops without crashing! They simply pause at the `yield` statement and wait for the next `.next()` call.
02

Two-way Communication

// 2. Two-way Communication
function* conversation() {
  const answer = yield "What is your name?";
  console.log("Hello, " + answer);
}

const chat = conversation();
console.log(chat.next().value); // "What is your name?"
chat.next("Subhajit");          // "Hello, Subhajit"
Generators aren't just for outputs. You can pass a value back into the generator via `.next(value)`, which becomes the result of the `yield` expression inside the function.
03

Async Iteration (ES2018)

// 3. Async Iteration (ES2018)
async function* fetchStream(urls) {
  for (const url of urls) {
    const res = await fetch(url);
    yield res.json();
  }
}

// Consumed with 'for await...of'
Async Generators combine the power of Async/Await with Generators, allowing you to stream asynchronous results one-by-one.
04

1. Core Usage: Generators

// Core syntax and usage for Generators: function* & yield
const feature = 'generators-function-star-yield';
console.log('Concept 66:', feature);
console.log('Active:', true);
Illustrates the fundamental invocation and syntax structure for Generators: function* & yield.
05

2. Defensive Handling & Edge Case

// Edge-case defensive handling
function handleSafe(input) {
  if (input === null || input === undefined) return 'safe-fallback';
  return String(input).trim();
}
console.log(handleSafe('generators-function-star-yield'));
console.log(handleSafe(null));
Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with Generators: function* & yield.
06

3. Clean Architecture & Production Pattern

// Production-grade pattern for Generators: function* & yield
const settings = Object.freeze({
  id: 'generators-function-star-yield',
  ready: true,
  timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);
Demonstrates clean, immutable production code avoiding unintended state mutations.

Real-World Engineering Takeaways

Lazy Evaluation: Processing massive files or datasets without loading them all into RAM.
State Machines: Implementing complex multi-step logic (like a multi-page form or game flow).
Concurrency: Libraries like `redux-saga` use generators to handle complex async side-effects.
Custom Iterables: Making objects iterable in a cleaner way than manual Protocol implementation.

Under the Hood: Engine & Memory Mechanics

How JavaScript Executes This
### **The Suspended State** **1. Context Retention:** - Unlike regular functions, a Generator's **Execution Context** is not destroyed when it returns or yields. - It is moved from the **Stack** to the **Heap**, preserving the values of all local variables and the **Instruction Pointer**. **2. Resumption:** - Calling `.next()` moves the context back to the **Stack**. - The **CPU** resumes execution from exactly where the last `yield` happened. **3. State Management:** - Generators are essentially a very efficient way to build a **Closure** that also remembers "where" it stopped in the code. - **Performance:** This state management is handled natively by the engine, making it faster than many manual state machine implementations.

Quick Knowledge Check

Test your understanding on these 10 questions (one by one):

Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model

What is the core purpose of Generators: function* & yield in JavaScript?

// Concept 66: Generators: function* & yield
// Understanding the core mental model
1 / 10