How do you write a basic generator function?
Short answer
Add an asterisk after 'function' to make it a generator; calling it doesn't run the body immediately but returns an iterator, and each yield pauses execution, resuming from that point on the next next() call.
Advertisement
AModel answer
Add an asterisk after 'function' to make it a generator; calling it doesn't run the body immediately but returns an iterator, and each yield pauses execution, resuming from that point on the next next() call.
function* countTo3() {
yield 1;
yield 2;
yield 3;
}
const gen = countTo3();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2Real-world example
Lazily generating a sequence of values one at a time instead of computing and storing them all upfront.
Likely follow-ups
- What does gen.next() return once the generator is finished?
Related topics