Lazy and infinite sequences
naturals() never ends, yet the program finishes: take returns after 5 items, which also closes the generators behind it.
A generator function (function*) can pause at each yield and resume later; calling it returns a generator object that is both an iterator and an iterable, which makes lazy and even endless sequences a few lines of code.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a generator chunks(array, size) that yields slices of size items. [...chunks([1, 2, 3, 4, 5], 2)] should give [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ].
Write an infinite generator idMaker(prefix) that yields "user-1", "user-2", ... and log the first three ids using destructuring.
Write a generator cycle(items) that repeats the items forever, and use a for...of with a counter to log the first 5 values of cycle(["red", "green"]).
Explain it without notes
What happens, step by step, when you call a generator function and then call next() three times?
Why are generators described as lazy, and why does that make infinite sequences possible?
How do next(value), return() and throw() let the caller control a generator?
What does yield* do, and when would you use it?
Preview
Console
Nothing logged yet.Expected console output
[ 2, 4, 6, 8, 10 ]
[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ]