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