What is a generator function in JavaScript?

QuestionsQuestions8 SkillsProDate Range GeneratorAug, 24 2025
0174

A generator function in JavaScript is a special type of function that can be paused and resumed, allowing it to yield multiple values over time instead of returning a single value. It is defined using the function* syntax. When called, a generator function returns a generator object, which can be used to control the execution of the function.

Here are some key features of generator functions:

  • Yielding Values: Instead of using return, generator functions use the yield keyword to produce a value and pause execution.
  • Stateful: The function maintains its state between invocations, allowing it to remember where it left off.
  • Iteration: Generator functions can be iterated using a for...of loop or by calling the next() method on the generator object.

Here’s a simple example of a generator function:

function* countUpTo(max) {
    let count = 1;
    while (count <= max) {
        yield count;
        count++;
    }
}

const counter = countUpTo(5);
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
console.log(counter.next().value); // 3

In this example, the countUpTo generator function yields numbers from 1 to the specified maximum value. Each call to next() retrieves the next value in the sequence.

0 Comments

no data
Be the first to share your comment!