Skip to content

Chapter 24 of 33

Generators

Build lazy controllable sequences with function*, yield, delegation, and two-way flow.

36 minutes 10 quick checksBy Subha Prasad
Lesson 24 of 33Course navigation

Lesson content

Read, practise, then check your understanding

Calling a generator function returns an iterator without running the full body. Each next resumes until yield or completion.

Lazy values

function* range(start, end) {
  for (let value = start; value < end; value += 1) yield value;
}

for (const value of range(1, 4)) console.log(value);

yield* delegates to another iterable. Values passed to next(value) become the previous yield expression’s result, enabling two-way protocols, while return completes iteration. Generators simplify lazy/infinite sequences and traversal state but must still release resources when consumers stop; use try/finally when cleanup matters.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes generator function?
Which JavaScript term matches this description: A function* that returns a controllable iterator.
Which statement best describes yield?
Which JavaScript term matches this description: Suspension that produces the next iterator value.
Which statement best describes yield*?
Which JavaScript term matches this description: Delegation to another iterable or generator.
Which statement best describes generator return?
Which JavaScript term matches this description: Completion producing a done result, usually excluded from for...of.
Which statement best describes lazy sequence?
Which JavaScript term matches this description: Values produced on demand rather than stored eagerly.

0 of 10 checks passed

Your progress is saved on this device.

Generators | JavaScript Lesson | Subha Prasad