What is "function*" in JavaScript?

The function* declaration defines a generator function that returns a Generator object. Unlike regular functions, generators can pause execution with yield and resume later, making them powerful for controlling program flow and creating iterators.

Syntax

Generator functions can be declared with function* in three equivalent ways:

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

How Generator Functions Work

When called, a generator function doesn't execute immediately. Instead, it returns a generator object with methods like next() to control execution step by step.

Basic Example

<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

Understanding yield and next()

The yield keyword pauses the function and returns a value. Each call to next() resumes execution until the next yield or function end.

function* simpleGenerator() {
    console.log("Start");
    yield 1;
    console.log("Middle");
    yield 2;
    console.log("End");
    return 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: true}
Start
{ value: 1, done: false }
Middle
{ value: 2, done: false }
End
{ value: 3, done: true }

Common Use Cases

Generators are useful for creating custom iterators, handling asynchronous operations, and implementing lazy evaluation where values are computed on demand.

Conclusion

Generator functions with function* provide powerful control over execution flow through yield and next(). They're essential for creating iterators and managing complex asynchronous workflows in JavaScript.

Updated on: 2026-03-15T21:46:15+05:30

345 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements