javascript · level 3 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A function pauses at every .
Writing next() by hand is fiddly. A generator writes it for you. Put a star after function and, inside, yield each value in turn. Calling the generator runs nothing yet: it hands back an iterator.
Each next() runs the body as far as the next yield, hands that value out and freezes on the spot, local variables and all. When the body ends, done becomes true. Generators are iterable, so for...of and spread work too.
function* trafficLight() {
console.log("starting");
yield "red";
yield "amber";
yield "green";
}
const light = trafficLight();
console.log("made it");
console.log(light.next().value);
console.log([...light]); Spread carries on from wherever the generator paused, so it only collects amber and green.
guess first
Logs between the yields. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function* steps() {
console.log("A");
yield 1;
console.log("B");
yield 2;
console.log("C");
}
const run = steps();
console.log(run.next().value);
console.log(run.next().value);
console.log(run.next().done);
your turn
Your turn. Generate order ids.
Fill in the keyword that hands out each id and pauses, then choose a short prefix such as ORD.
fix it
No even numbers came out. Can you fix it?
- Spread collects the values a generator hands out. How many does this one hand out?
returnends a generator at once, and spread ignores a returned value.- Change
return n;toyield n;, then press run.
nailed it
your functions can pause now. :D
function*makes a generator that returns an iterator.- Each
next()runs to the nextyield, then pauses. returnends a generator; spread ignores its value.
new words in your collection
- generator
- yield
This lesson isn’t saved. A free account remembers every lesson you finish.