Generators and Iterators
A generator function can pause and resume, yielding a sequence of values one at a time instead of computing and returning them all at once.
function* countTo(n) {
for (let i = 1; i <= n; i++) {
yield i;
}
}
for (const number of countTo(3)) {
console.log(number);
}
Expected output
1
2
3
Generators are what power for...of's ability to iterate arrays,
strings, and maps under the hood, and are useful for representing a
sequence too large (or infinite) to build as an array upfront.