Skip to content Skip to sidebar Skip to footer

Semantics Of Return Value Of A Generator

I have a problem with understanding the semantics of 'return' in a generator. I understood it as the final, hence last value. function* gen() { yield 'foo'; return 'bar'; } fo

Solution 1:

No, you cannot get the return value from a for … of loop. You could however try

function* gen() {
  yield 1;
  yield 2;
  return "done";
}
function* genAndLogResult() {
  const val = yield* gen();
  console.log(val);
}

for (const x of genAndLogResult()) {
  console.log(x + 40);
}

Solution 2:

From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function%2A

A return statement in a generator, when executed, will make the generator done. If a value is returned, it will be passed back as the value. A generator which has returned will not yield any more values.

It makes sense that the for-loop skips the "done" step. For example:

function* gen() { yield "foo" }
const inst = gen()
inst.next() // { done: false, value: "foo" }
inst.next() // { done: true, value: undefined }

function* gen() { yield "foo"; return "bar" }
const inst = gen()
inst.next() // { done: false, value: "foo" }
inst.next() // { done: true, value: "bar" }

Since generators don't necessarily have a return statement, you wouldn't want the last iteration of the for-loop to always have to deal with the final undefined value.


Solution 3:

The yield keyword is used to pause and resume a generator function.

function* gen() {
    yield "foo";
    yield "bar";
}

for (const x of gen()) {
    console.log(x);
}

It prints foo and bar. If you want more details about yield click here


Post a Comment for "Semantics Of Return Value Of A Generator"