JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

Generators & Iterators

javascript
senior
generators

What are Generators in JavaScript and when would you use them?

generators
iterators
yield
lazy-evaluation
es6
Quick Answer

Generators are functions that can pause execution and resume later, yielding multiple values over time. They're defined with function* syntax and return an iterator. Use cases include lazy evaluation, infinite sequences, and custom iterables.

Detailed Explanation

Generator Basics:

  • Defined with function* syntax
  • Use yield to pause and emit values
  • Return an iterator with next() method
  • Can receive values via next(value)

Iterator Protocol:

  • next() returns { value, done }
  • Generator completes when function returns or no more yields

Use Cases:

  1. Lazy evaluation: Generate values on demand
  2. Infinite sequences: Memory-efficient infinite data
  3. Custom iterables: Make objects work with for...of
  4. Async flow control: Conceptual predecessor to async/await (the generator + promise pattern inspired the spec)
  5. State machines: Manage complex state transitions

ES2025 Iterator Helpers: Generators now have built-in methods like map(), filter(), take(), drop(), reduce(), find(), and flatMap() via Iterator.prototype. These work directly on any generator without custom utility functions.

Code Examples

Basic generator syntaxJavaScript
function* numberGenerator() {
  console.log('Starting');
  yield 1;
  console.log('After first yield');
  yield 2;
  console.log('After second yield');
  yield 3;
  console.log('Ending');
  return 'done';
}

const gen = numberGenerator();

console.log(gen.next()); // 'Starting', { value: 1, done: false }
console.log(gen.next()); // 'After first yield', { value: 2, done: false }
console.log(gen.next()); // 'After second yield', { value: 3, done: false }
console.log(gen.next()); // 'Ending', { value: 'done', done: true }
console.log(gen.next()); // { value: undefined, done: true }

Real-World Applications

Use Cases

Paginated API Data Fetching

Using async generators to lazily fetch pages from REST APIs, yielding results one page at a time to reduce memory usage for large datasets

Stream Processing Pipelines

Building composable data transformation pipelines using generator chains where each stage yields to the next, enabling backpressure-aware processing

Stateful UI Wizards

Implementing multi-step form wizards where each yield represents a step, with bidirectional communication via next(value) for user input

Mini Projects

Lazy CSV Parser

intermediate

Build a CSV parser using generators to lazily read and parse rows, supporting filtering and transformation via chained generators or Iterator Helpers

Cooperative Task Scheduler

advanced

Implement a cooperative multitasking scheduler using generators as coroutines with task priorities, cancellation, and inter-task communication

Industry Examples

Redux Saga

Uses generators as the core mechanism for managing side effects in Redux, yielding declarative effect descriptions interpreted by middleware

RxJS

Supports converting generators to Observables via from(), enabling lazy sequences to be composed with reactive operators

Resources

MDN - Generator

docs

JavaScript.info - Generators

article
Previous
Explain JavaScript's prototype chain and how inheritance works.
Next
What are Proxies in JavaScript and how can they be used?
PrevNext