Iterables and Iterators

Updated · 8 min read
hardES2026javascriptiteratorsiterablessymbol-iterator

An iterable is an object that can be looped over with for...of: arrays, strings, Maps, Sets and many more. An iterator is the object that actually hands out the values, one at a time, each time you call its next() method. The agreement between them is the iteration protocol, and it is what for...of, spread (...), array destructuring, Array.from, Promise.all and new Map(...) all use under the hood. Implementing the protocol makes your own objects work with every one of those features.

In One Minute

  • An iterable has a method under the key Symbol.iterator that returns an iterator.
  • An iterator has a next() method returning { value, done }; done: true means finished.
  • for...of, spread, destructuring, Array.from, Map/Set constructors and Promise.all all consume iterables.
  • Make your own object iterable by defining [Symbol.iterator](), most easily as a generator.
  • Iterators are lazy and usually one-pass: values are produced on demand, and a used-up iterator stays done.

The Protocol

RoleRequirement
IterableHas a [Symbol.iterator]() method that returns an iterator
IteratorHas a next() method that returns an iterator result
Iterator resultAn object { value, done }: done is false while there are values, true at the end
Optional: return()Called when a consumer stops early (break, an error), for cleanup

Driving an Iterator by Hand

manual.js▶ Try it
const fees = [120, 85];
const iterator = fees[Symbol.iterator]();
 
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
Output
{ value: 120, done: false }
{ value: 85, done: false }
{ value: undefined, done: true }
{ value: undefined, done: true }

Explanation: calling the array's [Symbol.iterator]() method gives a fresh iterator. Each next() returns the next value with done: false; after the last value, it returns done: true, and it keeps doing so. This is exactly what for...of does for you.

What for...of Does

for-of-desugared.js▶ Try it
const students = new Set(["Navika", "Srihitha"]);
 
for (const name of students) console.log("for...of:", name);
 
const it = students[Symbol.iterator]();
let result = it.next();
while (!result.done) {
  console.log("by hand:", result.value);
  result = it.next();
}
Output
for...of: Navika
for...of: Srihitha
by hand: Navika
by hand: Srihitha

The while loop is (almost exactly) what the engine runs for for...of.

Built-In Iterables

IterableIterates over
Array, typed arraysValues (also .keys(), .entries())
StringCode points (so emoji stay whole)
Map[key, value] entries (also .keys(), .values())
SetValues
arguments, NodeListItems
Generator objectsYielded values

Plain objects are not iterable: for (const x of {}) throws a TypeError. Use Object.entries(obj), which returns an array.

Everything That Consumes Iterables

consumers.js▶ Try it
const grades = new Set([9, 10, 11]);
 
console.log([...grades]);
const [first, second] = grades;
console.log(first, second);
console.log(Array.from(grades, (g) => `Grade ${g}`));
console.log(new Map([["Navika", 9], ["Advitha", 11]]).get("Advitha"));
console.log(Math.max(...grades));
console.log(Object.fromEntries(new Map([["a", 1]])));
console.log(await Promise.all(new Set([Promise.resolve(1), 2])));
Output
[9, 10, 11]
9 10
['Grade 9', 'Grade 10', 'Grade 11']
11
11
{ a: 1 }
[1, 2]

Any object that follows the protocol works with all of these, which is the point of having one standard protocol.

Making Your Own Iterable

Give an object a [Symbol.iterator] method that returns an object with next():

custom.js▶ Try it
class FeeSchedule {
  constructor(firstGrade, lastGrade, base, step) {
    Object.assign(this, { firstGrade, lastGrade, base, step });
  }
 
  [Symbol.iterator]() {
    let grade = this.firstGrade;
    const { lastGrade, base, step, firstGrade } = this;
    return {
      next() {
        if (grade > lastGrade) return { value: undefined, done: true };
        const value = { grade, fee: base + (grade - firstGrade) * step };
        grade++;
        return { value, done: false };
      },
    };
  }
}
 
const schedule = new FeeSchedule(9, 12, 400, 15);
for (const { grade, fee } of schedule) console.log(`Grade ${grade}: $${fee}`);
console.log([...schedule].length, Math.max(...[...schedule].map((r) => r.fee)));
Output
Grade 9: $400
Grade 10: $415
Grade 11: $430
Grade 12: $445
4 445

Each call to [Symbol.iterator]() creates a new iterator with its own grade counter, so the schedule can be iterated many times. The next lesson shows how a generator writes the same thing in a few lines:

generator-preview.js
*[Symbol.iterator]() {
  for (let grade = this.firstGrade; grade <= this.lastGrade; grade++) {
    yield { grade, fee: this.base + (grade - this.firstGrade) * this.step };
  }
}

Laziness and One-Pass Iterators

Iterators produce values on demand: nothing is computed until next() is called. That allows infinite sequences, as long as the consumer stops:

lazy.js▶ Try it
const receiptNumbers = {
  [Symbol.iterator]() {
    let n = 1000;
    return { next: () => ({ value: `R-${++n}`, done: false }) };
  },
};
 
const taken = [];
for (const r of receiptNumbers) {
  taken.push(r);
  if (taken.length === 3) break;
}
console.log(taken);
Output
['R-1001', 'R-1002', 'R-1003']

Never spread an infinite iterable ([...receiptNumbers] would run forever). Iterator helpers like take(3) make this safer (see the iterator helpers lesson).

Iterators are usually one-pass. An iterable (like an array) can produce many iterators, but each iterator can be walked only once:

one-pass.js▶ Try it
const iterator = [1, 2, 3].values();
console.log([...iterator]);
console.log([...iterator]);
 
const array = [1, 2, 3];
console.log([...array], [...array]);
Output
[1, 2, 3]
[]
[1, 2, 3] [1, 2, 3]

Stopping Early: return()

When a consumer stops before the end (break, return, an exception, or destructuring only the first few values), it calls the iterator's optional return() method, giving it a chance to clean up, such as closing a file or a database cursor:

return.js▶ Try it
function openRows(rows) {
  let i = 0;
  return {
    [Symbol.iterator]() { return this; },
    next() {
      return i < rows.length ? { value: rows[i++], done: false } : { value: undefined, done: true };
    },
    return() {
      console.log(`closing cursor after ${i} rows`);
      return { value: undefined, done: true };
    },
  };
}
 
for (const row of openRows(["Navika", "Srihitha", "Advitha"])) {
  console.log("row:", row);
  if (row === "Srihitha") break;
}
 
const [firstRow] = openRows(["Zoe", "Ana"]);
console.log("first:", firstRow);
Output
row: Navika
row: Srihitha
closing cursor after 2 rows
closing cursor after 1 rows
first: Zoe

This iterator returns itself from [Symbol.iterator](), the usual pattern for objects that are their own iterator (like generator objects and array iterators). Generators get return() behavior automatically through try...finally.

In Practice

The Fee Tracker's PaymentLedger keeps payments in an internal array but exposes them only through iteration: callers can loop, spread and destructure, but can't change the internal list:

ledger.js▶ Try it
class PaymentLedger {
  #payments = [];
  add(name, amount) {
    this.#payments.push(Object.freeze({ name, amount }));
    return this;
  }
  [Symbol.iterator]() {
    return this.#payments.values();
  }
  *byStudent(name) {
    for (const p of this.#payments) if (p.name === name) yield p;
  }
}
 
const ledger = new PaymentLedger().add("Navika", 120).add("Advitha", 45).add("Navika", 60);
 
console.log([...ledger].length);
console.log([...ledger.byStudent("Navika")].map((p) => p.amount));
const total = Array.from(ledger).reduce((sum, p) => sum + p.amount, 0);
console.log(total);
Output
3
[120, 60]
225

[Symbol.iterator] simply returns the internal array's own iterator (values()), and byStudent is a generator method, previewing the next lesson.

Common Mistakes

for...of on a plain object. Objects aren't iterable. Loop over Object.entries(obj).

Reusing a consumed iterator. It's empty on the second pass. Keep the iterable or collect to an array.

Spreading an infinite iterable. It never ends. Stop with break or take.

Forgetting done: true. An iterator that never reports done loops forever.

Practice

Challenge: Make a Countdown class whose instances are iterable, yielding numbers from start down to 1, and use it with spread and for...of.

Show solution
countdown.js▶ Try it
class Countdown {
  constructor(start) {
    this.start = start;
  }
  [Symbol.iterator]() {
    let current = this.start;
    return {
      next: () => (current > 0 ? { value: current--, done: false } : { value: undefined, done: true }),
    };
  }
}
 
const c = new Countdown(3);
console.log([...c]);
for (const n of c) console.log("T-minus", n);
Output
[3, 2, 1]
T-minus 3
T-minus 2
T-minus 1

Quick check: Iterators

3 questions
1What makes an object iterable?
2What does an iterator's next() return when it's finished?
3What happens if you spread the same array iterator (arr.values()) twice?

Key Takeaways

TaskCode
Get an iteratorconst it = iterable[Symbol.iterator]()
Next valueit.next() → { value, done }
Make iterable[Symbol.iterator]() { return { next() { ... } }; }
Collect values[...iterable] or Array.from(iterable)
Cleanup on early stopreturn() { ...; return { done: true }; }

Was this tutorial helpful?

Lesson 108 of 139