Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading