Generator functions in Javascript are special functions that can generate a sequence of values.
Generator function is a special type of function that can be paused in the middle of its execution and resumed later. This is done using the yield keyword. Generator functions are useful for creating
iterators, which are
objects that can be used to iterate over a sequence of values.
Here is an example of a generator function:
let arr=[1,2,3,4,5];
function* test() {
yield arr[4];
yield arr[3];
yield arr[2];
}
let result=test();
console.log(result.next()); // { value: 5,done:false}
console.log(result.next()); // { value: 4,done:false}
console.log(result.next()); // { value: 3,done:false}
console.log(result.next()); // { value: undefined,done:true}
for(let item of test())
{
console.log('using for of ',item); // using for of 5 (then 4,3, undefined)
}
In above code we have created our own sequence of array items which can be iterated via next() method or by using generator function in 'for loop'
Note:- In 'for loop' we have to use generator function i.e test() as shown in above code and not the variable containing the test function i.e result variable.
function* printTillCount() {
let id=0;
while(id<3)
yield id++;
}
let resultNew=printTillCount();
console.log(resultNew.next()); // {value: 0, done: false}
console.log(resultNew.next()); // {value: 1, done: false}
console.log(resultNew.next()); // {value: 2, done: false}
console.log(resultNew.next()); // {value: undefined, done: true}
// we can also iterate above in for of loop using generator function 'printTillCount()'
Generator functions are a powerful tool that can be used to create iterators and other types of functions that need to be able to pause and resume their execution.
Here are some of the benefits of using generator functions:
1. They can be used to create iterators, which are objects that can be used to iterate over a sequence of values.
2. They can be used to create asynchronous functions, which can handle multiple requests at the same time.
3. They can be used to create functions that need to be able to pause and resume their execution.
Here are some of the limitations of using generator functions:
1. They can be more difficult to understand than traditional functions.
2. They cannot be used as constructors.
3. They cannot be used with `eval()` or `arguments`.
Conclusion:
Overall, generator functions are a powerful tool that can be used to create efficient and reusable code. However, they are not always the best choice, and it is important to understand their limitations before using them.