Open In App

Generator Function in ES6

Last Updated : 10 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A Generator Function is a special type of function that can pause its execution and later resume from where it left off. Instead of returning a single value, it returns an iterator object which can yield multiple values over time using the yield keyword.

Example

JavaScript
function* generator() {
    yield 'First value';
    yield 'Second value';
    return 'Done';
}
const gen = generator();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next()); 

Output
{ value: 'First value', done: false }
{ value: 'Second value', done: false }
{ value: 'Done', done: true }
  • The generator function is defined using function* and uses yield to produce values sequentially.
  • When gen.next() is called the first time, it yields the object { value: 'First value', done: false }.
  • The second call to gen.next() yields { value: 'Second value', done: false }.
  • The third call returns the final value { value: 'Done', done: true }, indicating the generator is finished.

Infinite Sequence Generator

This code demonstrates an infinite generator function that continuously yields increasing values. It keeps generating numbers, starting from 0, each time .next() is called.

JavaScript
function* infinite() {
    let i = 0;
    while (true) {
        yield i++;
    }
}
const gen = infinite();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);

Output
0
1
2
3
4
  • The while(true) loop ensures that the generator function runs forever, continuously yielding values.
  • Each time gen.next().value is called, the generator returns the current value of i.
  • The value of i starts at 0 and increases by 1 with each iteration.
  • No End to the Sequence Since the loop is infinite, the generator will never stop yielding values unless manually terminated.

Delegating Generators

This code shows how to use yield* to delegate to another generator function. The main generator yields values from the sub generator before continuing with its own yield.

JavaScript
function* sub() {
    yield 'Sub value 1';
    yield 'Sub value 2';
}
function* main() {
    yield* sub();
    yield 'Main value';
}
const gen = main();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value); 

Output
Sub value 1
Sub value 2
Main value
  • The sub generator yields two values: 'Sub value 1' and 'Sub value 2'.
  • The main generator uses yield* sub() to yield all values from sub sequentially.
  • After exhausting sub, main yields an additional value: 'Main value'.
  • Calling gen.next().value retrieves each value in order: first 'Sub value 1', then 'Sub value 2', and finally 'Main value'.

Generators with Asynchronous Operations

This code demonstrates how to use a generator function that yields a promise, simulating asynchronous behavior. The promise resolves after a delay, and the result is logged using .then().

JavaScript
function* asyncG() {
    yield new Promise((resolve) => 
        setTimeout(() => resolve('Async value'), 1000));
}
  
const gen = asyncG();
gen.next().value.then(console.log);

Output

Async value
  • The asyncG generator yields a promise that resolves with 'Async value' after a 1-second delay.
  • The gen.next() starts the generator and returns the promise.
  • .value of the yielded promise is accessed and its .then() method is used to handle the resolved value.
  • After 1 second, the promise resolves, and 'Async value' is logged to the console.
Screenshot-2025-01-25-095753
Generators with Asynchronous Operations

Stateful Iteration with Generators

This code demonstrates a generator function counter that starts from a given value and increments by the values passed into it. It uses the yield keyword to pause and resume its execution, allowing dynamic changes to the counter.

JavaScript
function* counter(start = 0) {
    let count = start;
    while (true) {
        count += yield count;
    }
}
const gen = counter();
console.log(gen.next().value);
console.log(gen.next(2).value);
console.log(gen.next(3).value); 

Output
0
2
5
  • The first gen.next() call starts the generator with the default value of count (0). It yields count (0).
  • The second call gen.next(2) passes 2 into the generator, which is added to count. Now count becomes 2, and 2 is yielded.
  • The third call gen.next(3) passes 3 into the generator, which is added to count. Now count becomes 5, and 5 is yielded.
  • Each time, the generator function continues from where it left off and updates the count with the value passed to yield.

Iterating Over a Collection

This code uses a generator function to iterate over an object's key-value pairs. It allows you to process each property of an object one at a time using a for...of loop.

JavaScript
function* objectE(obj) {
    for (const [key, value] of Object.entries(obj)) {
        yield [key, value];
    }
}

const gen = objectE({ a: 1, b: 2, c: 3 });
for (const [key, value] of gen) {
    console.log(`${key}: ${value}`);
}

Output
a: 1
b: 2
c: 3
  • The generator function objectE uses Object.entries(obj) to get an array of key-value pairs, then yields each pair individually.
  • When you call objectE with an object (e.g., { a: 1, b: 2, c: 3 }), it returns an iterator that produces each key-value pair.
  • The for...of loop iterates over the generator, printing each key and value in the format "key: value".

Explore