What are generator functions in JavaScript?

Generator functions in JavaScript allow you to pause and resume function execution, providing powerful control over program flow. Unlike regular functions that run to completion, generators can yield values multiple times and maintain their internal state between calls.

Syntax

Generator functions are defined using the function* syntax with an asterisk. The asterisk can be placed in different positions:

function* myGenerator() {}
// or
function *myGenerator() {}
// or
function*myGenerator() {}

How Generator Functions Work

Generator functions use the yield keyword to pause execution and return a value. When called, they return a generator object that implements the iterator protocol with a next() method.

<html>
<body>
<script>
function* display() {
    var num = 1;
    while (num < 5) {
        yield num++;
    }
}

var myGenerator = display();

document.write(myGenerator.next().value);
document.write("<br>" + myGenerator.next().value);
document.write("<br>" + myGenerator.next().value);
document.write("<br>" + myGenerator.next().value);
document.write("<br>" + myGenerator.next().value);
</script>
</body>
</html>
1
2
3
4
undefined

Generator Object Methods

The generator object returned by a generator function has several methods:

function* simpleGenerator() {
    yield 1;
    yield 2;
    yield 3;
}

const gen = simpleGenerator();

console.log(gen.next());  // {value: 1, done: false}
console.log(gen.next());  // {value: 2, done: false}
console.log(gen.next());  // {value: 3, done: false}
console.log(gen.next());  // {value: undefined, done: true}
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: undefined, done: true }

Practical Example: ID Generator

function* idGenerator() {
    let id = 1;
    while (true) {
        yield `ID_${id++}`;
    }
}

const createId = idGenerator();

console.log(createId.next().value);
console.log(createId.next().value);
console.log(createId.next().value);
ID_1
ID_2
ID_3

Key Benefits

Generator functions provide several advantages:

  • Memory Efficiency: Values are generated on-demand rather than all at once
  • Flow Control: Execution can be paused and resumed as needed
  • Infinite Sequences: Can generate unlimited values without memory issues
  • Asynchronous Control: Useful for managing async operations

Conclusion

Generator functions offer powerful control over execution flow and memory usage. They're particularly useful for creating iterators, managing asynchronous operations, and generating sequences of values efficiently.

Updated on: 2026-03-15T21:39:51+05:30

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements