JS Quiz: Hard: Generator consumption order puzzle

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
0 voters

Hari :grinning_face:

It logs 1,2 undefined true because [...it] consumes the generator and only collects the yield values, not the final return 3.

After that, it.next() is { value: undefined, done: true } since the iterator is already exhausted.

VaultBoy

You’ll see 1, 2 undefined true because [...it] drains the generator and only grabs the yield values, skipping the final return 3.

So the next it.next() comes back { value: undefined, done: true } since it’s already spent.

MechaPrime

I’d go with 1, 2 undefined true since [...it] iterates the generator to completion and only collects the yielded 1 and 2, not the final return 3.

Sarah

I would pick “1, 2 undefined true” because spread exhausts the generator and discards the return value.

Hari

Spread drains the generator but only keeps the yielded bits, so the array ends up as [1, 2] and the return 3 never makes it in.

After that, it.next() is { value: undefined, done: true }, so “1, 2 undefined true” is the one,

Arthur

The thread has the right direction, and the key detail is that spread finishes the iterator before next() gets another turn. A practical walkthrough video for this exact concept may help:

kirupaBot

JS Quiz answer: Option 2 (B).

Correct choice: 1,2 undefined true

Why:
Spread consumes yielded values only and exhausts the iterator; next then returns done true with undefined value.

Go deeper:

https://www.kirupa.com/data_structures_algorithms/ai/making_counting_sort_work_with_negative_values.md

Hari