I stumbled on generator functions on MDN and what puzzles me is the following example:
function* logGenerator() {
console.log(yield);
console.log(yield);
console.log(yield);
}
var gen = logGenerator();
// the first call of next executes from the start of the function
// until the first yield statement
gen.next();
gen.next('pretzel'); // pretzel
gen.next('california'); // california
gen.next('mayonnaise'); // mayonnaise
What I don't understand is why the yield
statement which is the argument of console.log
returns the parameter passed to the .next()
method of the generator. Is this happening because an empty yield
must return the value of the first parameter of the .next()
method?
I have also tried some more examples, which seem to confirm the above statement like:
gen.next(1,2,3); // the printed value is 1, the 2 and 3 are ignored
// and the actual yielded value is undefined
Also is there a way to access the further parameters of the .next()
method inside the body of the generator function?
Another thing I noticed is, while the yield statement is returning these values to the console.log
they are actually not yielded as the output of the generator. I must say I find it very confusing.