JavaScript Iterators and Iterables: Symbol.iterator, the Iteration Protocol and Custom Iterables
How for...of, spread and destructuring really work: iterables, iterators and result objects, Symbol.iterator, writing custom iterable classes and functions, laziness, one-shot iterators, the return() method for cleanup on break, and the most common iteration errors.
kvi5hnuCode Sprout team member6 min readOn this page
for...of, the spread operator, array destructuring, Array.from, new Set(...) and Promise.all all work with arrays, strings, Maps and Sets, and with your own objects too, if they follow one small protocol. Understanding that protocol explains error messages like "x is not iterable", makes your own data structures loop-friendly, and is the foundation for generators (the next two articles).
Three roles
![for...of calls playlist[Symbol.iterator]() to get an iterator, then calls next() repeatedly; each result object has a value and a done flag, and done: true ends the loop. Leaving the loop early calls iterator.return()](https://code-sprout-content.laxmi.solutions/asset/2026/11/js-iteration-protocol-kv6dq7opsw7w2tf7.png)
- An iterable is an object with a method whose key is the well-known symbol
Symbol.iterator(article 19). Calling that method returns an iterator. - An iterator is an object with a
next()method. - Each
next()call returns an iteration result: an object{ value, done }.done: falsemeansvalueis the next item;done: truemeans the sequence has ended.
You can drive the protocol by hand:
const playlist = ["intro", "verse", "chorus"];
const it = playlist[Symbol.iterator]();
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
{ value: 'intro', done: false }
{ value: 'verse', done: false }
{ value: 'chorus', done: false }
{ value: undefined, done: true }
for (const song of playlist) does exactly this: get an iterator, call next() until done is true, and assign each value to song.
What's iterable, and what consumes iterables
console.log(typeof [][Symbol.iterator], typeof "hi"[Symbol.iterator], typeof new Map()[Symbol.iterator]);
console.log(typeof {}[Symbol.iterator]);
try {
for (const x of { a: 1 }) {}
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
function function function
undefined
TypeError: {(intermediate value)} is not iterable
Iterable: arrays, strings, Map, Set, typed arrays, arguments, DOM collections like NodeList, the results of map.entries(), array.keys(), str.matchAll(), and generator objects.
Not iterable: plain objects. Use Object.keys, Object.values or Object.entries (which return arrays) to loop over them.
Consumers of iterables:
| Feature | Example |
|---|---|
for...of | for (const x of items) |
| Spread | [...items], f(...items) |
| Array destructuring | const [first, second] = items |
| Constructors and factories | Array.from(items), new Set(items), new Map(entries), Object.fromEntries(entries) |
| Promise combinators | Promise.all(items), Promise.race(items) |
yield* | inside generators (next article) |
Making a class iterable
Implement [Symbol.iterator]() and return an object with next():
class Countdown {
constructor(start) {
this.start = start;
}
[Symbol.iterator]() {
let current = this.start; // state lives in each iterator
return {
next: () => current > 0
? { value: current--, done: false }
: { value: undefined, done: true },
};
}
}
const launch = new Countdown(3);
console.log([...launch], [...launch], Math.max(...launch));
const [first, ...rest] = new Countdown(4);
console.log(first, rest);
console.log(Array.from(new Countdown(3), (n) => n * 10), new Set(new Countdown(2)));
[ 3, 2, 1 ] [ 3, 2, 1 ] 3
4 [ 3, 2, 1 ]
[ 30, 20, 10 ] Set(2) { 2, 1 }
Notice that launch can be spread twice. Each spread calls [Symbol.iterator]() again and gets a fresh iterator with its own current. Keeping the position in the iterator, not on the Countdown object, is what makes the class reusable, and lets two loops over the same object run independently.
The next article shows a much shorter way to write this method with a generator: *[Symbol.iterator]() { for (let i = this.start; i > 0; i--) yield i; }.
Iterators are usually one-shot
Built-in iterators are themselves iterable: their [Symbol.iterator]() returns the same iterator. So you can pass a half-used iterator to for...of or spread, and it continues from where it was:
const it = [1, 2, 3, 4][Symbol.iterator]();
const head = it.next().value;
console.log(head, [...it], [...it]);
1 [ 2, 3, 4 ] []
The second spread gives [] because the iterator is exhausted. This is the most common iteration bug: storing an iterator (or a generator object) and trying to loop over it twice. Arrays can be iterated many times; an iterator only once. If you need multiple passes, keep the iterable, or copy the values into an array first.
When you write your own iterators, add [Symbol.iterator]() { return this; } so they work with for...of too. Iterators that inherit from the built-in Iterator.prototype get it automatically (article 93).
Laziness
Iterators compute values on demand. Nothing is produced until someone calls next(), and a consumer can stop at any time. That lets you represent sequences that are huge, expensive or infinite without building an array:
function lines(text) {
let pos = 0;
return {
[Symbol.iterator]() { return this; },
next() {
if (pos >= text.length) return { value: undefined, done: true };
const end = text.indexOf("\n", pos);
const stop = end === -1 ? text.length : end;
const line = text.slice(pos, stop);
pos = stop + 1;
return { value: line, done: false };
},
};
}
for (const line of lines("alpha\nbeta\ngamma\ndelta")) {
console.log(line);
if (line === "beta") break; // "gamma" and "delta" are never sliced
}
alpha
beta
Compared with text.split("\n"), which builds every line up front, the iterator only does the work the loop actually uses. This pattern scales to reading files, paginated APIs (with async iterators, Part 13) and streams.
Cleaning up: the return() method
Loops don't always run to the end. break, return, a thrown exception, or destructuring that takes only a few values all stop early. If your iterator holds a resource (an open file, a database cursor, a lock), it needs to know. When a consumer stops early, it calls the iterator's optional return() method:
function reader(items) {
let i = 0;
return {
[Symbol.iterator]() { return this; },
next() {
return i < items.length ? { value: items[i++], done: false } : { value: undefined, done: true };
},
return() {
console.log(" cleanup: closing reader");
return { value: undefined, done: true };
},
};
}
for (const x of reader(["a", "b", "c"])) {
console.log(x);
if (x === "b") break;
}
const [only] = reader(["x", "y"]);
console.log(only);
for (const x of reader(["done"])) console.log(x);
try {
for (const x of reader(["p", "q"])) throw new Error("boom");
} catch (err) {
console.log(err.message);
}
a
b
cleanup: closing reader
cleanup: closing reader
x
done
cleanup: closing reader
boom
In the last case, return() runs as the exception leaves the loop, so the cleanup line appears before the catch block logs boom. The rules:
return()is called onbreak,return,throwand partial destructuring.- It is not called when the iterator finishes normally (
done: true), because the iterator already knows it's done. Put cleanup in both places, or use a generator withtry...finally(article 92), which handles both automatically. return()must return an object (usually{ done: true }).
Iteration errors you'll meet
const broken = {
[Symbol.iterator]() {
return { next() { return 5; } }; // should return { value, done }
},
};
try {
[...broken];
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
TypeError: Iterator result 5 is not an object
| Message | Usual cause |
|---|---|
x is not iterable | looping over a plain object, undefined or a number; or a missing [Symbol.iterator] |
Result of the Symbol.iterator method is not an object | [Symbol.iterator] returned a non-object (often forgot return) |
Iterator result ... is not an object | next() returned something other than { value, done } |
x is not a function on next | the iterator object has no next method |
Another classic: for...in instead of for...of iterates keys (indexes as strings, article 42), not values.
Common questions
What's the difference between an iterable and an iterator?
An iterable can produce iterators (it has [Symbol.iterator]()); an iterator does the iterating (it has next()). An array is iterable but not an iterator; array.values() returns an iterator that is also iterable.
Why can I loop over an array twice but not over map.entries()?
Each loop over the array calls [Symbol.iterator]() and gets a new iterator. map.entries() is already an iterator; its [Symbol.iterator]() returns itself, so the second loop starts at the end.
How do I make a plain object iterable?
Add a [Symbol.iterator] method, as in the code below. Often it's clearer to loop over Object.entries(obj) instead.
*[Symbol.iterator]() {
yield* Object.entries(this);
}
Are iterators faster than arrays?
Not for small collections: array methods are highly optimized. Iterators win when they avoid work, such as not building an intermediate array, stopping early, or handling data too big to fit in memory.
Summary
- An iterable has
[Symbol.iterator](), which returns an iterator; an iterator hasnext(), which returns{ value, done }. for...of, spread, array destructuring,Array.from,new Set/new Map,Promise.allandyield*all consume iterables.- Plain objects aren't iterable; use
Object.entriesand friends. - Keep iteration state in the iterator so each loop is independent; built-in iterators are one-shot and return themselves from
[Symbol.iterator](). - Iterators are lazy: they compute values on demand and can be infinite.
- An optional
return()method runs when a consumer stops early, for cleanup.
Practice Questions
What does this code print?
const it = "ab"[Symbol.iterator]();
console.log([...it].length, [...it].length);
Answer
2 0. The first spread exhausts the iterator, and the second spread reuses the same, finished iterator.
Make this object iterable over its members, so [...team] gives ["Ana", "Bo"].
const team = { members: ["Ana", "Bo"] }
Answer
Add the code below, delegating to the array's iterator.
[Symbol.iterator]() {
return this.members[Symbol.iterator]();
}
Why is return() not called after a loop that runs to completion?
Answer
return() signals early termination. When next() itself reports done: true, the iterator knows iteration ended and should already have cleaned up.
const [a, b] = new Set([1, 2, 3, 4]): how many times is next() called?
Answer
Twice for a and b. Then, because destructuring stopped before the iterator was done, it calls the iterator's return() method if one exists. (Set iterators have none, so nothing else happens.)
Previous: JavaScript Timers: setTimeout, setInterval, Cancelling, Delays, Throttling and Scheduling
Next: JavaScript Generators: function*, yield, yield*, Infinite Sequences and Recursive Generators

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.