Learn the concept
Generators & Iterators
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.
Generator Basics:
function* syntaxyield to pause and emit valuesnext() methodnext(value)Iterator Protocol:
next() returns { value, done }Use Cases:
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.
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 }Using async generators to lazily fetch pages from REST APIs, yielding results one page at a time to reduce memory usage for large datasets
Building composable data transformation pipelines using generator chains where each stage yields to the next, enabling backpressure-aware processing
Implementing multi-step form wizards where each yield represents a step, with bidirectional communication via next(value) for user input
Build a CSV parser using generators to lazily read and parse rows, supporting filtering and transformation via chained generators or Iterator Helpers
Implement a cooperative multitasking scheduler using generators as coroutines with task priorities, cancellation, and inter-task communication