Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 487
Faizanur Rahman Avatar asked May 25 '26 18:05

Faizanur Rahman


1 Answers

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.

like image 143
Barmar Avatar answered May 27 '26 06:05

Barmar