A generator function in JavaScript (or Python, since both use similar concepts) is a special type of function that can pause its execution and later resume. Instead of returning a single value like a normal function, it yields multiple values over time, one at a time, which makes it very memory-efficient for handling large datasets or sequences.
Here’s a breakdown:
Key Features
- Defined using
function*(asterisk) in JavaScript. - Uses
yieldto produce a value and pause execution. - Returns an iterator (an object with a
next()method). - Can maintain state between executions.
Example in JavaScript
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const gen = numbers();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
value→ the yielded valuedone→ indicates if the generator is finished
Use Cases
- Iterating over large datasets without loading everything into memory.
- Implementing lazy evaluation (compute values only when needed).
- Creating infinite sequences (like Fibonacci numbers).
