← Back to JavaScript, page 4

javascript-0071 · Medium mid

How does the iteration protocol work in detail, including early exit with return(), and what are iterator helpers?

An iterable returns a fresh iterator from [Symbol.iterator](), and the iterator's next() gives { value, done }. When a loop exits early with break, return, or a throw, the language calls the iterator's optional return() method so it can clean up. Iterator helpers such as map, filter, take, and toArray build lazy pipelines directly on iterators in current runtimes.

Full answer

The protocol has two layers. An iterable has a [Symbol.iterator]() method that returns an iterator. An iterator has a next() method that returns { value, done }. Many built-in iterators are also iterable and return themselves, so they can be used in for...of but only once. An array, by contrast, returns a new iterator each time, so it can be looped repeatedly.

Consumers such as for...of, spread, destructuring, Array.from, Map, and Promise.all call next() until done is true. Destructuring stops after the items it needs.

Cleanup is the part many candidates miss. If a consumer stops before done becomes true, because of break, return, a thrown error, or destructuring fewer items, it calls the iterator's optional return() method. A generator turns this into running its finally blocks. A custom iterator can release a file handle, a database cursor, or a lock in return(). When the loop finishes normally, return() is not called.

Iterators can be lazy. A chain of generators, or the iterator helper methods map, filter, take, drop, flatMap, toArray, and reduce on Iterator.prototype, processes one item at a time through the whole pipeline. With take(3) on an infinite source, only three items are ever pulled. These helpers are available in Node.js 22 and current browsers; check support for older targets.

Errors in the iterator or the consumer follow the same cleanup rule, so always release resources in return() or finally.

javascript
class Resource {
  constructor(items) {
    this.items = items;
  }
  [Symbol.iterator]() {
    let index = 0;
    const items = this.items;
    console.log('open');
    return {
      next: () => (index < items.length ? { value: items[index++], done: false } : { value: undefined, done: true }),
      return: () => {
        console.log('close (return called)');
        return { done: true };
      },
    };
  }
}

for (const item of new Resource(['a', 'b', 'c'])) {
  console.log('item', item);
  if (item === 'b') break;
}
console.log('--- full loop');
for (const item of new Resource(['x'])) console.log('item', item);
console.log('--- destructuring');
const [firstOnly] = new Resource([1, 2, 3]);
console.log(firstOnly);

function* withCleanup() {
  try {
    yield 1;
    yield 2;
  } finally {
    console.log('generator finally ran');
  }
}
for (const n of withCleanup()) {
  console.log('generator value', n);
  break;
}

const once = [10, 20][Symbol.iterator]();
console.log([...once], [...once]);
const list = [10, 20];
console.log([...list], [...list]);

function* naturals() {
  let n = 1;
  while (true) yield n++;
}
const pipeline = naturals()
  .filter((n) => n % 2 === 0)
  .map((n) => n * n)
  .take(4);
console.log(pipeline.toArray());
console.log(naturals().drop(2).take(3).reduce((sum, n) => sum + n, 0));

Run with Node.js v24.22.1 as js-71.js; two runs gave identical output. Output: open item a item b close (return called) --- full loop open item x --- destructuring open close (return called) 1 generator value 1 generator finally ran [ 10, 20 ] [] [ 10, 20 ] [ 10, 20 ] [ 4, 16, 36, 64 ] 12

Key points

  • Iterable returns an iterator; the iterator's next() returns { value, done }.
  • Iterators from built-ins are one-shot; arrays give a fresh iterator each time.
  • Early exit (break, return, throw, partial destructuring) calls return() for cleanup.
  • Generators run finally blocks when return() is called.
  • Iterator helpers (map, filter, take, toArray) build lazy pipelines on iterators.

Common mistakes

  • Assuming return() runs when a loop finishes normally; it runs only on early exit.
  • Reusing a consumed iterator and getting an empty result the second time.
  • Opening a resource in [Symbol.iterator]() and never releasing it on early exit.
  • Using iterator helpers in an environment that does not support them yet.

Follow-ups

  • What does a generator do when return() is called while it is paused outside a try block?
  • How do async iterators and for await...of handle early exit?
  • How would you write a lazy take(n) helper without the built-in?

Tips

  • Mention the return() cleanup rule; it is the detail that shows depth.
  • Contrast an iterable (reusable) with a one-shot iterator.
  • Show a lazy pipeline over an infinite source to prove why laziness matters.