A generator is a JavaScript function form that can pause with yield and resume later, keeping its local variables between pauses. It produces values on demand instead of building an entire collection first, making it useful for large or potentially infinite data sequences. section 8.3
Generate values on demand
function* range(start = 0, finish = Number.POSITIVE_INFINITY) { for (let i = start; i < finish; i++) { yield i; } }\n\nconst numbers = range(1);\nnumbers.next().value; // 1\nnumbers.next().value; // 2\n\nA for...of loop can consume values until a chosen stopping point, so an infinite range does not need to finish producing. section 8.3
function *range(start = 0, finish = Number.POSITIVE_INFINITY) {
for(let i = start; i < finish; i++) {
yield i; #1
}
}
const num = range(1);
num.next().value; //-> 1
num.next().value; //-> 2
num.next().value; //-> 3
// or
for (let n of range(1)) { #2
console.log(n);
if(n === threshold) { #3
break;
}
}// -> 1,2,3,...
Inspect the range generator, its next() calls, and its for...of usage. section 8.3
Generators can also transform values, compose nested generators with yield*, and traverse structures such as trees. Their lazy iterators offer another approach to asynchronous code alongside promises and functional reactive programming. section 8.3 section 8.5











