Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Symbol.iterator — the synchronous iteration protocol

Symbol.iterator is the well-known symbol identifying an iterator-producing method. It lets a custom object work with for...of and array spread. An iterable supplies an iterator, while the iterator supplies successive results through next().

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

iterable[Symbol.iterator]()
({ [Symbol.iterator]() { return iterator; } })

Symbol.iterator is a well-known symbol, not a function. It is the key of an iterable object's [Symbol.iterator]() method. That method returns an iterator used by consumers including for...of and array spread ([...iterable]). The string key "Symbol.iterator" is not the same key.

An iterable supplies this method, whereas an iterator has a next() method. Each next() call must return a result object: done indicates completion, and value contains the current element while iteration continues. When done: true, consumers such as for...of do not process value as an element. Having next() alone does not make an object iterable.

In the example, every [Symbol.iterator]() call creates a separate counter. Both spreads therefore produce 1,2,3. An iterator need not itself be iterable; to make it iterable, it can provide [Symbol.iterator]() returning this. Returning the same iterator does not guarantee that iteration restarts.

An ordinary object does not become iterable merely by having properties. An invalid implementation, such as returning a number instead of an object from next(), causes a TypeError when the protocol is used. This mechanism is synchronous; the asynchronous protocol uses the separate Symbol.asyncIterator.

Examples

const numbers = {
  [Symbol.iterator]() {
    let current = 1;
    return {
      next() {
        if (current <= 3) {
          return { value: current++, done: false };
        }
        return { done: true };
      }
    };
  }
};

console.log([...numbers].join(','));
console.log([...numbers].join(','));

Result

1,2,3
1,2,3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources