Advertisement
Beginner JavaScript, Iterators & Generators

Can you use a for...of loop directly on a generator's return value?

Short answer

Yes — a generator function's return value is itself an iterable (it implements Symbol.iterator returning itself), so for...of can consume it directly, automatically calling next() and stopping when done is true.

Save JavaScript mock interview
Advertisement
AModel answer
Yes — a generator function's return value is itself an iterable (it implements Symbol.iterator returning itself), so for...of can consume it directly, automatically calling next() and stopping when done is true.
function* countTo3() { yield 1; yield 2; yield 3; }
for (const n of countTo3()) {
  console.log(n); // 1, 2, 3
}
Real-world example
Iterating over a generator-produced sequence with the same clean syntax used for arrays.
Likely follow-ups
  • Does for...of capture the final 'return value' of a generator (the value alongside done: true)?
Related topics