What is function* in JavaScript ?
Last Updated :
12 Feb, 2024
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);
console.log(generator.next().value);
console.log(generator.next().value);
|
Share your thoughts in the comments
Please Login to comment...