What Are Generator Functions in JavaScript?
A generator function (declared with function*) can pause its execution at a yield statement and resume later, producing a sequence of values over time instea...
Published November 21, 2026
A generator function (function*) can pause with yield and resume later, producing values one at a time on demand. It returns an iterator, making lazy sequences and custom iteration easy.
The concept
Calling a generator does not run its body; it returns an iterator. Each next() runs until the next yield, returning that value, then pauses with its local state intact.
Because values are produced lazily, generators can represent infinite sequences or stream large data without loading it all.
Pause and resume
Practical examples
Basic generator
function* nums() { yield 1; yield 2; yield 3 }
[...nums()] // [1, 2, 3]Infinite sequence with take
function* ids() { let i = 0; while (true) yield i++ }
function* take(n, it) { for (const x of it) { if (n-- <= 0) return; yield x } }
[...take(3, ids())] // [0, 1, 2]Two-way communication
function* chat() { const name = yield 'name?'; yield `hi ${name}` }
const c = chat(); c.next(); c.next('Ada') // { value: 'hi Ada' }Common mistakes
- Forgetting a generator is single-use once exhausted.
- Spreading an infinite generator.
- Using generators where a simple array is clearer.
Key takeaways
- function* + yield = pausable function.
- Lazy, memory-friendly sequences.
- Returns an iterator.
FAQ
Generators vs async/await?
async functions are built on similar pause/resume mechanics.
What is yield*?
Delegates to another iterable or generator.