Generator iterator interface

suggest change

A generator object is both an iterator and an iterable. Calling a generator function creates the object without immediately running the function body.

function* numbers() {
  yield 5;
  yield 6;
}

const iterator = numbers();
console.log(iterator.next()); // { value: 5, done: false }
console.log(iterator.next()); // { value: 6, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

An iterable implements [Symbol.iterator]() and returns an iterator. Arrays, strings, maps, and sets are iterable. WeakMap and WeakSet deliberately are not iterable because exposing their contents would conflict with their weak-reference behavior.

Sending values into a generator

The argument passed to next() becomes the result of the suspended yield expression. The first call to next() starts the generator, so an argument supplied to that first call is ignored.

function* conversation() {
  const reply = yield "What is your name?";
  return `Hello, ${reply}`;
}

const conversationIterator = conversation();
console.log(conversationIterator.next());        // question; done is false
console.log(conversationIterator.next("Ada")); // greeting; done is true

Calling return(value) completes the generator early. Calling throw(error) resumes it by throwing at the suspended yield, allowing a try...catch inside the generator to handle the error.

Before async functions were standardized, libraries drove generators that yielded promises. For new code, prefer async and await; use generators when lazy, resumable iteration itself is the goal.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents