Generator Functions
A generator function can pause and resume.
It hands out values one at a time.
Think of a gumball machine. Turn the knob. Get one gumball. Turn again later.
function*
yield
next()
done
Why pause helps
Write a generator
Use function* with a star.
Use yield to pause and send a value.
What next returns
Each next call returns an object.
It has value and done.
done becomes true when there is nothing left.
Loop with for...of
Generators work nicely with for...of.
It keeps calling next for you.
Lazy lists
Generators can make long sequences without building a huge array first.
You only create the next value when asked.
Pass a value back
You can send a value into next.
That value becomes the result of yield.
Tip: Start with yield and next. Once those feel clear, bigger generator patterns get easier.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.