Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Iterators, Generators and Symbols

The iterable protocol

Reference for the JavaScript iterable protocol: objects with a [Symbol.iterator]() method, built-in iterables, custom iterables, and what consumes them.

An object is iterable if it has a method stored under the key Symbol.iterator that returns a fresh iterator. This is the contract that lets for...of, spread syntax, array destructuring, Array.from(), new Map(...), new Set(...) and Promise.all() walk over a collection without knowing what it is.

Strings, arrays, typed arrays, maps and sets are iterable out of the box. Plain objects are not. You can make your own classes iterable by adding a [Symbol.iterator]() method, and the easiest way to write it is as a generator.

JavaScript
const iterable = {
  [Symbol.iterator]() {
    /* return an iterator */
  },
};

Try it

JS A custom iterable

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS What is iterable?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

How it works

When a consumer receives a value, it calls value[Symbol.iterator]() once. If that is not a function, JavaScript throws a TypeError ("is not iterable"). Otherwise it repeatedly calls next() on the returned iterator until done is true.

Each call to [Symbol.iterator]() should return a new iterator, so the same collection can be looped over more than once, even at the same time. In the first example, range can be spread, destructured and looped over repeatedly.

Iterators that are also iterable

Built-in iterators (for example the result of array.values() or a generator object) are themselves iterable: their [Symbol.iterator]() returns this. That lets you pass an iterator anywhere an iterable is expected. The consequence is that such an object can be consumed only once, as the last line of the second example shows.

Usage notes

  • Consumers of iterables: for...of, spread ([...x], f(...x)), array destructuring, yield*, Array.from(), Object.fromEntries(), the Map, Set, WeakMap, WeakSet constructors, Promise.all() and its siblings, and Iterator.from().
  • Iterable is not array-like. An array-like has length and indexes but may not be iterable (and the other way round). Array.from() accepts both.
  • Plain objects need Object.keys(), Object.values() or Object.entries() first, or a custom [Symbol.iterator]().
  • Strings iterate by code point, not by UTF-16 unit, so [..."๐Ÿ˜€"].length is 1.
  • Generator methods (*[Symbol.iterator]() { yield ... }) are the least error-prone way to implement it, and they handle early exit for you.
  • Destructuring stops early: const [a, b] = iterable takes two values and then calls the iterator's return() method if it has one.
  • Async iterables use Symbol.asyncIterator and for await...of; see async generators.

Browser support

Iterables are part of ES2015 and supported in every current browser and in Node.js.