Skip to content
jshacks.dev
Fundamentals

Iterators and Iterables in JavaScript Explained Step by Step

An iterable has a Symbol.iterator method that returns an iterator whose next method gives value and done. See the protocol and early exit cleanup.

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

for (const item of collection) works on arrays, strings, sets, maps and generators with the same syntax, and fails on a plain object with TypeError: collection is not iterable. Spread, destructuring, Array.from(), new Set(...) and Promise.all() follow the same rule. All of them are built on one small protocol, and knowing it explains the error message, makes it possible to build your own collections that work with every one of those features, and shows why some loops can be run twice and others cannot. This post walks through the protocol with runnable code on Node.js 24, builds a custom iterable by hand and with a generator, covers early exit and cleanup, and ends on the lazy helpers that arrived in recent engines. The iteration methods on arrays are covered in the entries() post, and the symbol that names the hook is in the post on symbols.

The two parts of the protocol

An iterable is anything with a method stored under Symbol.iterator. Calling that method returns an iterator. An iterator is anything with a next() method that returns an object with value and done. A loop calls next() until done is true.

JavaScript
const list = ["a", "b"];
const iterator = list[Symbol.iterator]();

console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());

console.log(typeof list[Symbol.iterator]);
console.log(typeof iterator.next);
console.log(iterator[Symbol.iterator]() === iterator);
Text
{ value: 'a', done: false }
{ value: 'b', done: false }
{ value: undefined, done: true }
{ value: undefined, done: true }
function
function
true

The first two calls returned the items with done: false. The third returned done: true with an undefined value, and further calls stay done. Iterators are themselves iterable, which is why the last line prints true: an iterator's [Symbol.iterator]() returns itself, so a loop can consume an iterator directly.

What consumes an iterable

Anything that accepts an iterable uses the same two steps.

JavaScript
const set = new Set([3, 1, 2]);

for (const value of set) console.log("for...of", value);

const [first, ...rest] = set;
console.log(first, rest);
console.log([...set].map((n) => n * 2));
console.log(Array.from("héy"));
console.log(Math.max(...set));
console.log(new Map([["a", 1]]).entries().next());

try {
  for (const x of { a: 1 }) console.log(x);
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
for...of 3
for...of 1
for...of 2
3 [ 1, 2 ]
[ 6, 2, 4 ]
[ 'h', 'é', 'y' ]
3
{ value: [ 'a', 1 ], done: false }
TypeError: {(intermediate value)} is not iterable

A set, a string and a map's entries all worked in loops, spread, destructuring and Array.from(). A plain object does not define Symbol.iterator, so the loop fails at the very start, with a message that describes the expression it could not iterate. To loop over an object's contents, iterate Object.keys(), Object.values() or Object.entries(), which return arrays.

Writing an iterable by hand

A class becomes iterable by defining [Symbol.iterator](). The method can return any object with a conforming next().

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

  [Symbol.iterator]() {
    let current = this.start;
    const { end, step } = this;

    return {
      next() {
        if (current > end) return { value: undefined, done: true };
        const value = current;
        current += step;
        return { value, done: false };
      },
    };
  }
}

const range = new Range(1, 10, 3);

console.log([...range]);
console.log([...range]);
console.log(Math.max(...new Range(1, 5)));

for (const n of new Range(1, 3)) console.log("n =", n);
Text
[ 1, 4, 7, 10 ]
[ 1, 4, 7, 10 ]
5
n = 1
n = 2
n = 3

Each call to [Symbol.iterator]() creates a new state with its own current, so the same range can be iterated repeatedly and by several loops at once. That is the difference between an iterable, which is reusable, and an iterator, which is a single pass. If the method returned a shared iterator stored on the instance, the second spread would be empty.

Generators make this short

A generator function returns an object that is both an iterator and an iterable, and yield replaces the manual state.

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

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

function* take(iterable, count) {
  let taken = 0;
  for (const value of iterable) {
    if (taken++ >= count) return;
    yield value;
  }
}

function* naturals() {
  let n = 1;
  while (true) yield n++;
}

console.log([...new Range(0, 20, 5)]);
console.log([...take(naturals(), 4)]);
Text
[ 0, 5, 10, 15, 20 ]
[ 1, 2, 3, 4 ]

The generator version is six lines shorter, and it makes infinite sequences possible: naturals() never ends, and take stops after four items, so the spread finishes. The values are produced only when asked for, which is the other benefit of iteration: nothing is built in memory ahead of time.

Iterators are one pass

Because an iterator holds state, a second loop over the same iterator continues where the first ended.

JavaScript
const gen = (function* () {
  yield 1;
  yield 2;
  yield 3;
})();

for (const n of gen) {
  console.log("first loop", n);
  if (n === 2) break;
}

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

const array = [1, 2, 3];
console.log([...array], [...array]);
Text
first loop 1
first loop 2
[]
[]
[ 1, 2, 3 ] [ 1, 2, 3 ]

The loop consumed two items and then hit break, which closed the generator. That is the surprise in the output: the first spread was empty too, and not only the second one, because leaving a for...of early calls the iterator's return() method, and a generator that has been returned from never produces again. Arrays are iterables and not iterators, so each loop gets a fresh iterator and sees every item. If you need to stop early and keep going later, drive the iterator by hand with next(), which does not close it, or wrap the source in an iterable that makes a new iterator each time.

Early exit and return()

When a loop ends before the iterator reports done, because of break, return or a thrown error, the loop calls the iterator's return() method if it has one. This is the cleanup hook.

JavaScript
function* withResource() {
  console.log("open");
  try {
    yield 1;
    yield 2;
    yield 3;
  } finally {
    console.log("close");
  }
}

for (const n of withResource()) {
  console.log("got", n);
  if (n === 2) break;
}

const manual = {
  [Symbol.iterator]() {
    let i = 0;
    return {
      next: () => ({ value: i++, done: false }),
      return() {
        console.log("return() called");
        return { done: true };
      },
    };
  },
};

for (const n of manual) {
  if (n >= 1) break;
}

const [only] = manual;
console.log(only);
Text
open
got 1
got 2
close
return() called
return() called
0

The finally block of the generator ran when the loop broke, printing "close". The hand-written iterator's return() was called on break, and also by destructuring, which takes one value and then closes the iterator. This is how file handles, locks and network streams exposed as iterators get released when a consumer stops early. If you write an iterator that holds a resource, implement return(), and if you consume one, prefer for...of to manual next() calls so cleanup happens automatically.

Iterator helpers

Since Node.js 22, iterators from generators and from built-ins such as array.values() have helper methods that mirror array methods and work lazily.

JavaScript
function* naturals() {
  let n = 1;
  while (true) yield n++;
}

const result = naturals()
  .filter((n) => n % 2 === 1)
  .map((n) => n * n)
  .take(4)
  .toArray();

console.log(result);

console.log(Iterator.from([5, 6, 7]).drop(1).toArray());
console.log([10, 20, 30].values().some((n) => n > 25));
console.log(new Set([1, 2, 3]).values().reduce((sum, n) => sum + n, 0));
Text
[ 1, 9, 25, 49 ]
[ 6, 7 ]
true
6

The pipeline filtered, squared and limited an infinite sequence, and only four values were ever computed. Each helper returns a new iterator, and toArray() is the step that consumes it. These helpers belong to the ES2025 edition, so older runtimes need a polyfill or the generator versions above. The post on what changed in ES2025 lists them.

Pulling from an iterator by hand

Calling next() directly is the way to take a few items and leave the rest for later, and it is how parsers and tokenizers read from a stream of characters.

JavaScript
function* characters(text) {
  yield* text;
}

const source = characters("ab12");
const letters = [];

let step = source.next();
while (!step.done && /[a-z]/.test(step.value)) {
  letters.push(step.value);
  step = source.next();
}

console.log(letters);
console.log(step.value);
console.log([...source]);
Text
[ 'a', 'b' ]
1
[ '2' ]

The loop read letters until it met a digit, which it had already pulled and held in step. The remaining item was still available, because the iterator had not been closed. This lookahead pattern is why parsers often keep the current token in a variable. Using for...of with a break would have closed the source and lost the rest, so manual stepping is the right tool when you intend to resume.

Reading code that uses the protocol

When you meet an unfamiliar object in a loop, three questions identify what it is. Does it have a Symbol.iterator method? Does calling it return something with next()? And is the result a fresh state each time, or the same object returned again? The third decides whether the object can be looped twice. Libraries document this as "iterable" or "iterator" in their types: TypeScript's Iterable<T> is the reusable half, and Iterator<T> the one-pass half, and a function that accepts Iterable<T> is promising to ask for a new iterator when it needs one.

Where the protocol stops

Iteration is synchronous and one-directional. For asynchronous sources, such as a stream or a paginated API, there is a parallel protocol with Symbol.asyncIterator and for await...of. If you need random access or the length, an iterable does not give it, and an array does. If you need to iterate twice, make it an array or make it an iterable that creates a new iterator each time.

Do not build a custom iterator when an array would do, since an array is already iterable, supports random access and is easier to debug. The protocol is the right tool for lazy sequences, for large data that should not sit in memory and for collections with their own structure, such as trees.

The protocol is defined in the specification under iteration, and MDN's guide to iteration protocols covers both halves.

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.