Generator iteration
Learn to step through a generator with next().
The next() method
The .next() method of a generator object returns an object with two properties: value (the yielded value) and done (whether the generator has finished). While done is false, more values are available; when it becomes true, the generator is complete.
const g = counter();
g.next(); // { value: 1, done: false }
g.next(); // { value: 2, done: false }
g.next(); // { value: undefined, done: true } done and lazy evaluation
When the done property is true, the generator has finished. At this point value is undefined. A generator ends when it hits return or reaches the end of its body.
Thanks to this lazy evaluation, values are computed only when requested. You can write an infinite generator and consume just as much as you need; memory never fills up.
Exercise Call next() three times
Write a generator named numbers that yields 10 and 20. Create gen and call .next() three times, logging each result with console.log. The third call should show done as true.
Show example solution
function* numbers() {
yield 10;
yield 20;
}
const gen = numbers();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
Test yourself
-
What does gen.next() return?
function* counter() { yield 5; } const gen = counter(); gen.next();- Just the value 5
- An object { value, done }
- A Promise object
- An array
Show answer
An object { value, done } — Correct! .next() always returns an object shaped { value, done }.
-
Complete the next() call
function* counter() { yield 5; } const gen = counter(); const result = gen.____;Show answer
function* counter() { yield 5; } const gen = counter(); const result = gen.next(); -
Match the result object
- { value, done }
- result of next()
- done: true
- generator finished
- value: undefined
- final value