Glossary / Iterators

Iterators

An iterator is an object that advances through a sequence on demand. Its next() method returns an iterator result object with a value and Boolean done property. Iterators separate traversal state from the underlying data and can represent lazy, streaming, or infinite sequences without materializing them all at once.

Protocol and cleanup

const iterator = ["a", "b"][Symbol.iterator]();
iterator.next(); // { value: "a", done: false }
iterator.next(); // { value: "b", done: false }
iterator.next(); // { value: undefined, done: true }

An iterable supplies an iterator; an iterator itself need not be iterable, though generators are both. Iterators are often stateful and single-use. The optional return() method lets a consumer signal early completion so resources can be released. for...of invokes it on abrupt exit (such as break or a thrown exception) where available. The optional throw() method lets a consumer inject an error into generators.

Iterator consumers should not assume next() is cheap, synchronous, non-throwing, or finite. Custom iterators must return valid result objects and correctly indicate completion. Async iteration uses a related protocol whose next() results are awaited; do not confuse it with a sync iterator yielding Promises.

Interview questions

  1. What does next() return? An object with value and done fields.
  2. What is return() used for? Signaling early completion and enabling cleanup.
  3. Does iterator imply length or random access? No.
  4. What does for-of do on break? It asks the iterator to close via return() when present.

References