Introduced in ES6 version, generator functions are a special class of functions.
They can be stopped midway and then continue from where it had stopped.
Generator functions are declared with the function* keyword instead of the normal function keyword:
In normal functions, we use the return keyword to return a value and as soon as the return statement gets executed, the function execution stops:
In the case of generator functions, when called, they do not execute the code, instead they return a generator object . This generator object handles the execution.
The generator object consists of a method called next() , this method when called, executes the code until the nearest yield statement, and returns the yield value.
As one can see the next method returns an object consisting of value and done properties.
Value property represents the yielded value.
Done property tells us whether the function code is finished or not. (Returns true if finished)
Generator functions are used to return iterators. Let’s see an example where an iterator is returned