Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the * (star/asterisk) syntax after a yield mean in a recursive generator function? [duplicate]

Let's say I've created an ES6 generator

function *createFibonacciIterator(a = 0, b = 1) {
  yield b;
  yield *createFib(b, b + a); // <== QUESTION IS ABOUT THIS LINE
}

Then I use that generator to get the first 20 results

let fibber = createFibonacciIterator();
for (let ii = 0; ii < 20; ii++) {
    console.log(fibber.next());
}

If I leave the * out of the yield *createFib(b, b + a); line things break, which makes sense because I don't want yield an iterator but an actual value.

What's the technical meaning of * in the generator?

like image 267
Anthony Astige Avatar asked May 15 '16 14:05

Anthony Astige


2 Answers

When the * is used in the function declaration this mean that it is a generator function.

But when it is used as yield *myGeneratorFunction(), the definition of the Ecmascript 262 specification, Section 14.4.14, says that the engine tries to resolve the generator function calling the next() method of iterator returned by the generator function.

When the yield is used without the * (for example, yield createFibonacci()), it returns the value of the expression after the yield. In the example is the value returned of the createFibonacci.

like image 64
Henrique Limas Avatar answered Oct 19 '22 11:10

Henrique Limas


For most cases

yield *smth;

makes the same thing as

for (let x of smth) {
  yield x;
}
like image 35
Qwertiy Avatar answered Oct 19 '22 11:10

Qwertiy