JavaScript Generators — Control Flow with yield

Learn how generators work in JavaScript: creating custom iterators, lazy evaluation, async generators, and practical use cases.

JavaScript Advanced 📖 10 min

What Are Generators?

Generators are special functions that can be paused and resumed. They produce a sequence of values lazily (on demand).

Creating Generators

function* countTo(n) {
  for (let i = 1; i <= n; i++) {
    yield i;
  }
}

const counter = countTo(3);
console.log(counter.next()); // { value: 1, done: false }
console.log(counter.next()); // { value: 2, done: false }
console.log(counter.next()); // { value: 3, done: false }

for (const num of countTo(5)) {
  console.log(num); // 1, 2, 3, 4, 5
}

Async Generators

async function* fetchPages(url) {
  let page = 1;
  while (true) {
    const response = await fetch(`${url}?page=${page}`);
    const data = await response.json();
    if (data.length === 0) break;
    yield data;
    page++;
  }
}

for await (const page of fetchPages('https://api.example.com/posts')) {
  console.log(`Processing ${page.length} posts`);
}

Chunk Generator Pattern

function* chunks(array, size) {
  for (let i = 0; i < array.length; i += size) {
    yield array.slice(i, i + size);
  }
}

const batches = [...chunks([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)];
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →