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?
yield
statement behind. – Priestlydone: true
that the iterator returns. Returning it infor of
would cause either annoying special cases or inconsistencies because there is no difference between a function usingreturn undefined
,return
or no such statement at all so you can't differentiate between the intention to haveundefined
as last value or just ending, and in most cases you'dyield
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