what is generator function in javascript

11 months ago 36
Nature

A generator function in JavaScript is a special type of function that can be paused and resumed, and can yield multiple values. When called, generator functions do not initially execute their code. Instead, they return a special type of iterator, called a Generator. When a value is consumed by calling the generators next method, the Generator function executes until it encounters the yield keyword. The function can be called as many times as desired, and returns a new Generator each time. Each Generator may only be iterated once. The yield keyword can pause a generator function and return the value that follows yield, providing a lightweight way to iterate through values. A return statement in a generator, when executed, will make the generator finish. Generator functions are defined using the function* syntax.