Glossary / Iterables

Iterables

An iterable is a value that supplies an iterator through its [Symbol.iterator]() method. Iterables can be consumed by for...of, array spread, destructuring, and APIs such as Array.from. Arrays, strings, Maps, Sets, generators, and many DOM collections are iterable; ordinary plain objects are not iterable by default.

Iterable versus iterator

const range = {
  *[Symbol.iterator]() {
    yield 1; yield 2; yield 3;
  },
};
for (const value of range) console.log(value);

The iterable is the source/protocol; the iterator is the stateful traversal object returned by its method. Reusable collections usually return a fresh iterator each time. A generator object is both iterable and iterator, but is typically one-shot: after it is exhausted, iterating it again produces no values.

Strings iterate by Unicode code point, which can still split a user-perceived grapheme made of multiple code points. Spread eagerly consumes the full iterable, so it can hang or exhaust memory for an infinite/very large source. Iteration can throw, have side effects, or yield values lazily. for...of closes an iterator through return() on abrupt loop exit when available.

Engineering use

Use iterable APIs for pull-based sequence consumption and composable data sources. Make repeatability, laziness, ordering, and cleanup expectations clear. Do not assume an iterable has a known length or supports random access; those are properties of some collections, not the iterable protocol itself.

Interview questions

  1. What makes an object iterable? Its Symbol.iterator method returns an iterator.
  2. Is a plain object iterable? Not by default.
  3. Can spread consume an infinite iterable? It will never finish; use bounded iteration.
  4. Are every iterable and iterator identical? No; collections may return a new iterator each time.

References