Last Updated : 11 Jul, 2025
A generator function is a special type of function that can pause its execution at any point and resume later. They are defined using the function* syntax and use the yield keyword to pause execution and return a value.
Syntax
function* generatorFunction() {JavaScript
// Code that can yield multiple values
}
function* generate() {
yield 'Hello';
yield 'World';
return 'Done';
}
const generator = generate();
//Driver Code Starts
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
//Driver Code Ends
{ value: 'Hello', done: false } { value: 'World', done: false } { value: 'Done', done: true } { value: undefined, done: true }
Generators work by implementing the iterator protocol. When a generator function is called, it does not execute its body immediately. Instead, it returns a special iterator object called a generator object. This object can be used to control the execution of the generator.
function* example() {
console.log("Step 1");
yield 1;
console.log("Step 2");
yield 2;
console.log("Step 3");
return 3;
}
const gen = example();
//Driver Code Starts
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
//Driver Code Ends
Step 1 { value: 1, done: false } Step 2 { value: 2, done: false } Step 3 { value: 3, done: true }Key Features of Generators
Generators simplify the creation of custom iterators, making it easy to generate sequences of values.
JavaScript
function* fibonacci(limit) {
let [prev, current] = [0, 1];
while (limit--) {
yield current;
[prev, current] = [current, prev + current];
}
}
const fib = fibonacci(5);
console.log([...fib]);
In this example
Generators, in combination with libraries like co or with async/await syntax, help manage asynchronous flows.
JavaScript
function* asyncTask() {
console.log('Task 1');
yield new Promise(resolve =>
setTimeout(() =>
resolve('Task 2'), 1000));
console.log('Task 3');
}
const task = asyncTask();
task.next().value.then(console.log);
task.next();
Output:
Task 1
Task 3
Task 2
In this example
Generators can create infinite sequences that only compute values on demand.
JavaScript
function* infiniteSeq() {
let i = 0;
while (true) {
yield i++;
}
}
const sequence = infiniteSeq();
console.log(sequence.next().value);
//Driver Code Starts
console.log(sequence.next().value);
console.log(sequence.next().value);
//Driver Code Ends
In this example
infiniteSeq
generator creates an infinite sequence starting from 0
.next()
is called, it yields the current value of i
and then increments it (i++
).while (true)
, so it keeps generating numbers indefinitely.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4