freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #27 of 61

generators · function* · yield

LambdaVSThe Mutator
Lambda saysGenerators (function*) pause and resume with yield, producing values lazily.

A function* returns a generator. Each yield hands back a value and pauses until next() is called again. This makes lazy sequences, infinite streams, and custom iterators trivial — and generators are iterable, so for...of and spread consume them directly.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleWrite a generator that yields 1, 2, 3 and consume it with for...of.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>function* nums(){ yield 1; yield 2; yield 3; }
document.getElementById('o').textContent=[...nums()].join(' ');</script></body></html>
▶ Open the interactive comic issue
‹ Iterators · Symbol.IteratorDates · The Date Object ›