Functions That Can Be Paused
Generators are a special kind of function that can pause their execution midway, yield a value, and then resume from exactly where they left off. They are declared with an asterisk: function*.
Basic Syntax
function* generateSequence() {
console.log('Starting...');
yield 1; // Pause and return 1
console.log('Resumed!');
yield 2; // Pause and return 2
return 'Finished'; // Done!
}
const gen = generateSequence();
console.log(gen.next()); // { value: 1, done: false } -- "Starting..." logs
console.log(gen.next()); // { value: 2, done: false } -- "Resumed!" logs
console.log(gen.next()); // { value: 'Finished', done: true }
Generators Are Iterable
You can use them with for...of:
for (let value of generateSequence()) {
console.log(value); // logs: 1, then 2 (does NOT include the return value)
}
Why Use Generators?
- Custom iterators: Build your own iterable objects cleanly.
- Memory efficiency: Generate values on demand without creating a huge array in memory.
- Infinite sequences: Represent things like " all natural numbers " without pre-computing them.
Important
Think of yield as a " temporary return. " It hands a value back to the caller and freezes the function's state, unlike return which ends the function permanently.