8

Take a close look at code

function* NinjaGenerator() {
  yield "yoshi";
  return "Hattori";
}
for (let ninja of NinjaGenerator()) {
  console.log(ninja);
}

// console log : yoshi

Why "Hattori" is not logged ? Where as when we iterate over iterator using iterator.next() it show that value.

function* NinjaGenerator() {
  yield "yoshi";
  return "Hattori";
}

let ninjaIterator = NinjaGenerator();
let firstValue = ninjaIterator.next().value;
let secondValue = ninjaIterator.next().value;
console.log(firstValue, secondValue);

// console log: yoshi Hattori

Somebody please help me to understand how for-of loop work in iterator created by generator?

2
  • 1
    the return value is not a generator value. if you wnat to yield two values, put another yield statement behind. Commented Feb 5, 2022 at 10:28
  • The return value is a second-class citizen because it's just a "side note" to the done: true that the iterator returns. Returning it in for of would cause either annoying special cases or inconsistencies because there is no difference between a function using return undefined, return or no such statement at all so you can't differentiate between the intention to have undefined as last value or just ending, and in most cases you'd yield the things you want and then the function would return, and the return value shouldn't be looked at as part of the collection of things it yielded. Commented Feb 5, 2022 at 10:28

1 Answer 1

6

The value of next() has a done property that distinguishes the return value from the yielded values. Yielded values have done = false, while the returned values have done = true.

for-of processes values until done = true, and ignores that value. Otherwise, generators that don't have an explicit return statement would always produce an extra undefined in the for loop. And when you're writing the generator, you would have to code it to use return for the last iteration instead of yield, which would complicate it unnecessarily. The return value is rarely needed, since you usually just want consistent yielded values.

Sign up to request clarification or add additional context in comments.

2 Comments

Would you please tell me when do we need of return statement in generator function ?
It's practically never needed. A generator might theoretically use it to return some kind of summary after the iteration is done. But that means you have to use explicit calls to .next() to get the results, rather than normal iteration syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.