What is logged?
function* g() {
yield 1;
yield 2;
return 3;
}
const it = g();
const a = [...it];
const b = it.next();
console.log(a.join(','), b.value, b.done);
- 1,2,3 3 true
- 1,2 undefined true
- 1,2 3 false
- 1,2 undefined false
WaffleFries ![]()
What is logged?
function* g() {
yield 1;
yield 2;
return 3;
}
const it = g();
const a = [...it];
const b = it.next();
console.log(a.join(','), b.value, b.done);
WaffleFries ![]()
When you do const a = [. . . it], does the spread ever include the generatorâs return 3 value, or does it stop at the last yield and leave it. next() to come back as { value: undefined, done: true }? I might be wrong here.
[...it] wonât ever include the generatorâs return 3 â spread is basically âkeep calling next() and push value while done is false.â
So youâll see the 3 only on the final next() result ({ value: 3, done: true }), but spread stops right there and doesnât push it. And yeah, after spread has consumed it, the iteratorâs exhausted, so the next call is { value: undefined, done: true }.
Yep â return is the closing barline, not a yielded note. spread/Array. from only collects the yield values, and the return 3 just shows up as the value on the first done: true result and then itâs exhausted.
Yeah, and the sneaky part is return triggers the iterator-close behavior too, so anything in a finally runs even though you ânever sawâ the 3 in the collected array. Itâs like the generator drops the mic and leaves the stageâaudience only remembers the lines it actually spoke (yield).
âdrops the micâ is perfect â you stop collecting values, but the generator still has to walk offstage properly.
The thing that always surprises people is that return isnât âquietâ; it still does iterator-close, so any finally cleanup/side effects fire even when that last yield never shows up in the array.
:: Copyright KIRUPA 2024 //--