A generator function is a special type of function in JavaScript that allows you to produce a sequence of values on demand. Unlike regular functions that execute completely when called, generator functions can be paused and resumed, making them perfect for producing sequences of values over time.
It returns a generator object. These functions are written with function* syntax. The yield keyword is used within the generator is used to pause and resume the execution of code.
Syntax
The syntax for a generator function resembles a regular function, except for an asterisk (*) following the ‘function’ keyword and the incorporation of the ‘yield’ keyword within the function body.
yield 'Hello';
yield 'World';
}
const generator = generatorExample();
console.log(generator.next()); // { value: 'Hello', done: false }
console.log(generator.next()); // { value: 'World', done: false }
console.log(generator.next()); // { value: undefined, done: true }
In the example above, invoking generatorExample does not immediately execute its body; instead, it returns a generator object (iterator) on which we can call the next method. Each next invocation executes the function until the subsequent yield statement is reached, and the expression’s value is returned. When no more yield statements remain, the next method returns an object with an undefined value and a done property of true.
1. Generating Infinite Sequences:
Generators are also valuable for generating infinite sequences because they generate values as needed rather than computing them all at once.
let num = 1;
while (true) {
yield num++;
}
}
const numbers = naturalNumbers();
console.log(numbers.next().value); // 1
console.log(numbers.next().value); // 2
console.log(numbers.next().value); // 3
// ...
In this example, the naturalNumbers generator function generates an infinite sequence of natural numbers. Since the generator generates values as needed, we can obtain as many natural numbers as desired without exhausting memory.