Middle
How do generators work in JavaScript, as opposed to regular functions?
sobes.tech AI
Answer from AI
Generators in JavaScript are functions that can pause their execution and return intermediate values using the yield keyword. Unlike regular functions, which execute completely and return a single value, generators allow creating iterators with lazy value generation.
Example of a generator:
function* countUpTo(max) {
let count = 1;
while (count <= max) {
yield count; // pauses execution and returns the value
count++;
}
}
const counter = countUpTo(3);
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
console.log(counter.next().value); // 3
console.log(counter.next().done); // true
Thus, generators are useful for working with sequences of data that do not need to be computed all at once.