Open In App

What is function* in JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The function* keyword defines a generator function, which allows you to control the iteration process explicitly. Generator functions can yield multiple values over time, pausing and resuming execution as needed.

Example: Here, generateSequence() is a generator function defined using the function* syntax. When called, it returns a generator object. The next() method of the generator object is used to iterate through the sequence of yielded values (1, 2, and 3), and each value is printed to the console.

Javascript




function* generateSequence() {
    yield 1;
    yield 2;
    yield 3;
}
 
let generator = generateSequence();
 
console.log(generator.next().value); // Output: 1
console.log(generator.next().value); // Output: 2
console.log(generator.next().value); // Output: 3


Output

1
2
3

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads