Think of generator functions as functions being able to have a lot of consecutive return values that can be iterated over.
Generator functions are declared by adding the * (asterisk) sign after the function statement:
They “return” values through the yield statement. Here is an example:
You can harvest these values by using the iterator returned by the generator function and calling its next() method:
So what yield really does is define iteration steps that are returned when the next() function is called.
Actually the execution of the generator function is halted until the next value is requested.
So it’s entirely possible to have an endless loop in you generator:
You can iterate over the values with a for loop:
or a do while loop:
But the nicest way is using the for … of method:
These will all output
Generators and arrays
Arrays are already iteratables so you can choose to yield the whole array or its individual entries.
Note the subtle difference: in gen2() the array’s entries are yielded using yield*