Faizanur Rahman
Faizanur Rahman

Reputation: 534

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

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?

Upvotes: 7

Views: 1257

Answers (1)

Barmar
Barmar

Reputation: 781059

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.

Upvotes: 6

Related Questions