Creating a Generator Function


Creating a Generator Function

Sample code of a Generator function:

function* genFunc() {
    yield 'a';
    yield;
    yield 123;

    return "finished";
}


Function* Keyword

Generator functions look similar to regular functions, except that they have an asterisk (*) after the function keyword. This syntax may look similar to the pointer notation from other languages, but it is unrelated.


Notice how the function* keyword is used to declare a Generator function:

function* genFunc() { //notice the function* keyword

}


Yield Keyword

The yield keyword is used to pause the generator. The yield keyword may also be used to receive input and send output from the generator.


Notice how the yield keyword is used to pause and send several different types of output from the Generator function:

yield 'a'; //pauses the generator and sends out a value of 'a'
yield;     //pauses the generator and sends out an undefined value
yield 123; //pauses the generator and sends out a value of 123


Return Value

Generator Functions have an optional return value. Omitting the return value is equivalent to returning an undefined value. The return value of Generator functions is often left unused.

Notice the return value of the Generator function:

return "finished"; //return value of "finished"

results matching ""

    No results matching ""