Skip to content
jshacks.dev
Fundamentals

JavaScript Symbol iterator Explained With Real Examples

Symbol.iterator is the method that lets an object work with for...of, spread and destructuring. See the protocol, closing with return and the one-shot trap.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js and TypeScript logos.

Spread syntax, for...of, array destructuring, new Set(...) and Promise.all(...) look like five unrelated features, and they all do one thing: they ask a value for its Symbol.iterator method and call it. If the value has one, it works with every one of them. If it does not, each fails with the same TypeError. That single hook is how Array, String, Map, Set and generators plug into the language, and it is how you make your own class behave the same way. This post covers the protocol, a first iterable class, the closing hook that runs on break, the difference between an iterable and an iterator, why a plain object is not iterable, and a one-shot trap that makes the second loop silently empty. The examples assume Node.js 24.

The protocol in two parts

An iterable is an object with a method under the key Symbol.iterator. Calling it returns an iterator, which is an object with a next() method. Each call to next() returns { value, done }.

JavaScript
const iterable = {
  [Symbol.iterator]() {
    let n = 0;
    return {
      next() {
        n++;
        return n <= 3 ? { value: n * 10, done: false } : { value: undefined, done: true };
      },
    };
  },
};

console.log([...iterable]);

for (const value of iterable) {
  console.log(value);
}
Text
[ 10, 20, 30 ]
10
20
30

The object has no data of its own. The method creates a fresh counter each time, and the consumer drives it by calling next() until done is true. The value that comes with done: true is ignored by for...of and spread, so it is safe to leave it undefined. That is the entire contract, and everything in this post follows from it.

What consumes an iterable

ConsumerWhat it does with the iterator
for...ofCalls next() until done, and return() on early exit
Spread [...x], f(...x)Reads every value
Destructuring const [a, b] = xReads only as many values as it has names
Array.from(x)Reads every value, with an optional map function
new Set(x), new Map(x)Reads every value, Map expects pairs
Promise.all(x)Reads every value, then waits for them
yield* xDelegates to the iterator inside a generator
Object.fromEntries(x)Reads pairs

Destructuring is the one that reads lazily: const [first] = iterable calls next() once, then closes the iterator. The others take everything, so an infinite iterable hangs them, as the table suggests.

A class that is iterable

A generator method is the shortest way to write the hook, because a generator object is already an iterator.

JavaScript
class Range {
  constructor(start, end, step = 1) {
    this.start = start;
    this.end = end;
    this.step = step;
  }

  *[Symbol.iterator]() {
    for (let n = this.start; n <= this.end; n += this.step) {
      yield n;
    }
  }
}

const range = new Range(1, 9, 2);

console.log([...range]);
console.log(Math.max(...range));
console.log(Array.from(range, (n) => n * n));

const [first, second] = range;
console.log(first, second);
Text
[ 1, 3, 5, 7, 9 ]
9
[ 1, 9, 25, 49, 81 ]
1 3

The class stores three numbers and produces its values on demand, so a range of a billion numbers costs the same memory as a range of five. Every consumer works without the class knowing about any of them. Because the method is a generator, each call to range[Symbol.iterator]() starts from the beginning, so the same object can be looped many times.

Writing the iterator by hand

Sometimes you need more than a generator offers, such as a return() method for cleanup.

JavaScript
function countdown(from) {
  return {
    [Symbol.iterator]() {
      let n = from;
      return {
        next() {
          return n > 0 ? { value: n--, done: false } : { value: undefined, done: true };
        },
        return(value) {
          console.log("cleanup at", n);
          return { value, done: true };
        },
      };
    },
  };
}

for (const n of countdown(5)) {
  console.log(n);
  if (n === 3) break;
}

console.log([...countdown(2)]);
Text
5
4
3
cleanup at 2
[ 2, 1 ]

The break triggered the return() method, which printed cleanup at 2, because n had already moved on. When the loop ends because next() reported done, return() is not called, since the iterator finished by itself, and the spread on the last line shows no cleanup message. This is the hook that releases a file, a cursor or a lock when a consumer stops early. A generator gets the same behavior for free: break resumes it as if there were a return at the paused yield, so its finally blocks run.

Iterable and iterator are not the same thing

An iterator is the object with next(). An iterable is the object that hands one out. Built-in iterators are also iterables, because their Symbol.iterator returns the object itself.

JavaScript
const array = [1, 2, 3];
const iterator = array[Symbol.iterator]();

console.log(typeof iterator.next);
console.log(iterator[Symbol.iterator]() === iterator);
console.log(array[Symbol.iterator]() === array[Symbol.iterator]());
console.log(iterator.next());
console.log([...iterator]);
console.log([...iterator]);
Text
function
true
false
{ value: 1, done: false }
[ 2, 3 ]
[]

An array makes a new iterator on every call, so two loops over the same array both see everything. The iterator itself returns this from its Symbol.iterator, which is why you can pass an iterator to a for...of loop. But it keeps its position, so after one next() the spread sees only the remaining two values, and a second spread sees none. Passing an iterator where you meant to pass an iterable is how data gets lost.

The one-shot trap

If your iterable returns this from Symbol.iterator and keeps the position on the object, it can be read once.

JavaScript
class OneShot {
  constructor(items) {
    this.items = items;
    this.index = 0;
  }

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

  next() {
    return this.index < this.items.length
      ? { value: this.items[this.index++], done: false }
      : { value: undefined, done: true };
  }
}

const once = new OneShot(["a", "b"]);

console.log([...once]);
console.log([...once]);
Text
[ 'a', 'b' ]
[]

The second spread printed an empty array and raised no error. We hit this in a pagination helper that was logged once and then used again. Return a fresh iterator from Symbol.iterator, keeping the position in a local variable or in a generator, and the object is reusable. Return this only when the object really is a single pass stream, such as a reader, and name it so a reader of the code can tell.

Plain objects are not iterable

JavaScript
const prices = { pen: 2, ink: 5 };

try {
  [...prices];
} catch (e) {
  console.log(e.name);
}

try {
  for (const entry of prices) {
    console.log(entry);
  }
} catch (e) {
  console.log(e.name);
}

console.log([...Object.entries(prices)]);
console.log(Object.keys(prices)[Symbol.iterator] === Array.prototype[Symbol.iterator]);
Text
TypeError
TypeError
[ [ 'pen', 2 ], [ 'ink', 5 ] ]
true

A plain object has no Symbol.iterator, so spread and for...of throw a TypeError, with a message that says the value is not iterable. The usual fix is to iterate a derived array, as Object.entries() does. You can also add the hook to a specific object, but doing so on Object.prototype is a mistake, because it would change the behavior of every object in your program, including libraries that test for iterability to decide how to treat their input.

Checking whether something is iterable

JavaScript
const isIterable = (value) => value != null && typeof value[Symbol.iterator] === "function";

console.log(isIterable([]));
console.log(isIterable("ab"));
console.log(isIterable(new Map()));
console.log(isIterable({}));
console.log(isIterable(null));
console.log(isIterable(42));
Text
true
true
true
false
false
false

Strings are iterable by code point, which is why [..."😀"] has one item while "😀".length is 2. Numbers and null are not. The value != null guard matters because reading a property of null throws. This function is what libraries use to accept either one item or a list of them, and a string passes it, which surprises code that meant to treat a string as a single value.

Using it with yield*

Inside a generator, yield* delegates to any iterable, so one class can expose another's values.

JavaScript
class Playlist {
  constructor(...albums) {
    this.albums = albums;
  }

  *[Symbol.iterator]() {
    for (const album of this.albums) {
      yield* album.tracks;
    }
  }
}

const list = new Playlist({ tracks: ["a", "b"] }, { tracks: ["c"] });

console.log([...list]);
console.log(Array.from(list).length);
Text
[ 'a', 'b', 'c' ]
3

The playlist hides its nested structure behind one flat sequence. Callers loop over tracks without knowing about albums, and a change to how albums are stored does not change any caller. That is the design benefit of the protocol: it separates what you can read from how it is stored.

Choosing between the iteration options

You wantUse
Your own class to work with for...of and spreada *[Symbol.iterator]() generator method
Cleanup when the consumer stops earlya return() method, or a finally in a generator
Values on demand from an expensive sourcea generator
Several passes over the same datareturn a fresh iterator each time
A single pass streamreturn this and document it
Plain object keys and valuesObject.entries()

Practical rules we follow

Prefer a generator method over a hand-written iterator unless you need something it cannot express. Return a new iterator on each call so the object is reusable. Put cleanup in a finally block in the generator, not in the consumer. Never add Symbol.iterator to a built-in prototype. Do not mix up the object with its iterator when you pass values around: pass the iterable and let the consumer ask for the iterator. And name classes that return this as single use, since the alternative is a bug that shows up as an empty second loop.

Where Symbol.iterator stops being the right tool

It describes sequential, one-way reading. It cannot go backward, jump to an index, or report a length, so random access still needs an array. It is synchronous, so a source that must wait for data needs Symbol.asyncIterator, covered in Symbol.asyncIterator. It produces values and does not say anything about their type. And an iterable that reads from a changing source, such as a live array that grows during the loop, shows whatever the source holds at each step. The reference is in the MDN iteration protocols page and the ECMAScript specification.

Taggedsymbols
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.