If you are iterating through an iterator, using a for ... of
loop or something like Array.from
, the return value is going to be ignored. In other words, the value included in the end-of-iteration object (whose property done
is true
) is ignored.
function *gen(){
const val = yield 4;
return val * 2;
}
for (let value of gen()) {
console.log(value);
}
// output: 4
MDN function* documenation explained it very well:
A
return
statement in a generator, when executed, will make the generator done. If a value is returned, it will be passed back as the value. A generator which has returned will not yield any more values.
Reference:
- StackOverflow question: https://stackoverflow.com/a/37202835/873234