Generator Functions
Generator functions use function* and yield to produce sequences lazily, one value at a time.
Generator functions use function* and yield to produce sequences lazily, one value at a time.
function* counter(start = 0) {
while (true) yield start++;
}
const gen = counter(5);
gen.next().value; // 5
gen.next().value; // 6
function* range(s, e, step = 1) {
for (let i = s; i <= e; i += step) yield i;
}
[...range(1, 10, 2)]; // [1,3,5,7,9]
Generators are perfect for infinite sequences, pagination, and custom iterators.
More in JavaScript