In JavaScript, Iterating over generator using for-of loop ignore return statement why?
Asked Answered
S

1

7

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?

Splendent answered 5/2, 2022 at 10:18 Comment(2)
the return value is not a generator value. if you wnat to yield two values, put another yield statement behind.Priestly
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.Tiannatiara
P
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.

Pupiparous answered 5/2, 2022 at 10:29 Comment(2)
Would you please tell me when do we need of return statement in generator function ?Splendent
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.Pupiparous

© 2022 - 2024 — McMap. All rights reserved.