In JavaScript, a generator is a special type of function that can be paused and resumed during its execution. It allows you to define an iterative
algorithm by writing a function that can maintain its internal state and produce a sequence of values over time.
Generators are defined using a function syntax with an asterisk (*)
appended to the function
keyword
(function*
). Within the generator function, you can use the yield
keyword to produce a value and temporarily pause the
execution of the function, returning that value to the consumer.
function* generate() {
yield 1;
yield 2;
yield 3;
}
This example defines a generator function named generate
that produces a sequence of values: 1, 2, and 3.
Using a generator without the yield
keyword can limit the usefulness and potential benefits of generators. When you use the
yield
keyword without providing a value, it creates a yield expression that pauses the execution of the generator function and returns
undefined
as the yielded value.
function* range(start, end) {
while (start < end) {
yield; // Noncompliant: The generator yields undefined
start++;
}
}
Yielding without a value makes it harder for the generator consumer to understand the purpose or context of the yielded value. Instead, one should
always provide an explicit value with yield
(using undefined
when that is the intention) to make the generated sequence more
meaningful and informative.
function* range(start, end) {
while (start < end) {
yield start;
start++;
}
}