16. Generators
Generator functions are a new feature in ES6 that allow a function to generate many values over time by returning an object which can be iterated over to pull values from the function one value at a time.
A generator function returns an iterable object when it’s called.
It is written using the new *
syntax as well as the new yield
keyword introduced in ES6.
function *infiniteNumbers() {
let n = 1;
while (true) {
yield n++;
}
}
const numbers = infiniteNumbers(); // returns an iterable object
numbers.next(); // { value: 1, done: false }
numbers.next(); // { value: 2, done: false }
numbers.next(); // { value: 3, done: false }
Each time yield is called, the yielded value becomes the next value in the sequence.
Also, note that generators compute their yielded values on demand, which allows them to efficiently represent sequences that are expensive to compute, or even infinite sequences.