Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Iterator protocol: next(), return(), value, and done

Use `done`, not `value`, to detect the end of an iterator. Learn how to read a completion value and when `for...of` calls the optional `return()` method.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const iterator = iterable[Symbol.iterator]();
const result = iterator.next();
// result.done: completion flag; result.value: element or completion value
// When stopping early during manual iteration, call the optional method if callable:
if (typeof iterator.return === "function") {
  iterator.return();
}

The Iterator.next/return/value/done protocol describes how a synchronous iterator takes a step, reports completion, and can be closed early. An iterator has a next() method that returns a result object (IteratorResult). An iterable has a [Symbol.iterator]() method that returns an iterator. Having next() alone does not make an object iterable; a generator object is both. for...of gets the iterator and calls next() without arguments. What an argument means depends on the iterator's implementation.

done: false means value is an element, even if it is undefined. done: true means iteration is complete; value can then carry a completion value, which for...of does not pass to the loop body. Missing done counts as false, and for...of tests the property by converting it to a Boolean. Once exhausted, later next() calls should still report done: true, but the language does not enforce that.

The optional return(value) method signals that the caller is stopping and gives the iterator a chance to release resources. Its result typically has done: true and the supplied argument as value, but a generator can report done: false if it executes a yield in finally. On early exit through break or an exception from the loop body, for...of calls return() without arguments if present and ignores the result's done and value. It does not call return() on normal exhaustion or when next() itself throws.

Manual calls to next() do not close the iterator automatically: if you stop early, call return() yourself if it is callable. for...of throws a TypeError if next() or a closing call to return() returns a non-object. If closing was triggered by an exception from the loop body, the original exception takes precedence.

Examples

{
  function* sequence() {
    try {
      yield undefined;
      return "end";
    } finally {
      console.log("cleanup");
    }
  }

  function show(label, { done, value }) {
    console.log(`${label}: done=${done}, value=${value}`);
  }

  const full = sequence();
  show("next", full.next());
  show("next", full.next());
  show("next", full.next());

  for (const value of sequence()) {
    console.log(`loop: ${value}`);
    break;
  }

  const manual = sequence();
  manual.next();
  show("return", manual.return("stopped"));
}

Result

next: done=false, value=undefined
cleanup
next: done=true, value=end
next: done=true, value=undefined
loop: undefined
cleanup
cleanup
return: done=true, value=stopped

Three separate generators show normal exhaustion with the completion value `end`, automatic closing on `break`, and an explicit `return("stopped")`. Each started generator logs `cleanup` in its `finally` block.

Related lessons

  • JavaScript · Lesson 8 · Advanced · Version: 4

Sources