Skip to content
dreamcode
dreamcode
Map
Generators
Lesson 44 of 48
+15 XP on finish
JS EXPERTChapter 9 · JS Expert

Generators

A generator function, written function*, can pause itself with yield and pick up again later. Calling it does not run the body; it returns a generator object. Each next() runs until the next yield and returns { value, done }. Generators produce values lazily, so they can even describe endless sequences, and they work directly with for...of and spread.

Worked example

How it reads

  • yield hands out one value and pauses the function right there
  • Spreading [...countdown(3)] pulls values until the generator finishes
  • The endless ids generator is safe because values are only made on demand
Cloud tip: Never spread an endless generator. Take what you need with next() or a loop with a break.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Fill in evens so [...evens(7)] prints [ 0, 2, 4, 6 ].

Press Run to check your work.