Symbol.iterator: Making Anything Iterable
for...of, spread and destructuring all work by calling one method, and any object that has it can use all three.
The iteration protocol is a single method keyed by Symbol.iterator. Arrays, strings, Maps and Sets have it; plain objects do not, which is the whole reason for-of fails on them. Add the method and everything that consumes iterables starts working.
EXERCISE
1One Method Behind Three Features
Three pieces of syntax you use constantly are the same mechanism, and it is smaller than you would expect.
You have used for...of, spread and array destructuring for a long time without needing to know what connects them. They are all the same thing.
Each of these calls one method on the value:
const letters = ["a", "b", "c"];
for (const l of letters) { /* ... */ }
const copy = [...letters];
const [first, second] = letters;
The method is named by Symbol.iterator. You can confirm it is really there:
console.log(typeof letters[Symbol.iterator]); // "function"
console.log(typeof "hello"[Symbol.iterator]); // "function"
console.log(typeof new Map()[Symbol.iterator]); // "function"
console.log(typeof new Set()[Symbol.iterator]); // "function"
console.log(typeof ({ a: 1 })[Symbol.iterator]); // "undefined"
That last line is the answer to a question every beginner asks and few get a real answer to.
Why for...of fails on a plain object:
const user = { name: "Ada", age: 36 };
for (const item of user) {
console.log(item);
}
// TypeError: user is not iterable
The object is not broken and objects are not special-cased out. It simply has no Symbol.iterator method, so there is nothing for for...of to call. The error message is literally true rather than a figure of speech.
And why the usual workaround works:
for (const key of Object.keys(user)) { /* ... */ }
for (const [key, value] of Object.entries(user)) { /* ... */ }
Both return arrays, and arrays have the method. You are not iterating the object; you are iterating an array built from it.
Symbol.iterator is a symbol, not a string, and that is deliberate:
const user = { name: "Ada" };
user[Symbol.iterator] = function () { /* ... */ };
console.log(Object.keys(user)); // [ 'name' ]
console.log(JSON.stringify(user)); // {"name":"Ada"}
A symbol key does not show up in Object.keys, in for...in, or in . So adding iteration to an object cannot collide with a real property called iterator, and cannot accidentally change what your object serialises to. That is exactly what symbols exist for.
Almost nobody teaches this connection, which is a shame, because once you see it the three stop being three things to remember and become one small protocol you can join.
EXERCISE
2Making Your Own Object Iterable
Add the method and every feature that consumes iterables starts working on your object at once.
The method has one job: return an iterator, which is an object with a next method. The next exercise builds one by hand. This one uses a shortcut so the payoff arrives first.
Borrowing an existing iterator:
const team = {
name: "Platform",
members: ["Ada", "Grace", "Alan"],
[Symbol.iterator]() {
return this.members[Symbol.iterator]();
},
};
for (const member of team) {
console.log(member);
}
// Ada
// Grace
// Alan
Four lines. team is not an array and does not pretend to be one; it delegates to the array it already holds.
And now everything else works, with no further code:
console.log([...team]); // [ 'Ada', 'Grace', 'Alan' ]
const [lead, ...rest] = team;
console.log(lead, rest); // Ada [ 'Grace', 'Alan' ]
console.log(Array.from(team)); // [ 'Ada', 'Grace', 'Alan' ]
console.log(Math.max(...[1, 2, 3])); // spread works on any iterable
That is the reason the protocol is worth knowing. You implemented one method and gained for...of, spread, destructuring, Array.from, and every function that accepts an iterable. Nothing had to be told about your type.
A generator makes it shorter still:
const range = {
from: 1,
to: 5,
*[Symbol.iterator]() {
for (let i = this.from; i <= this.to; i++) {
yield i;
}
},
};
console.log([...range]); // [ 1, 2, 3, 4, 5 ]
The star marks it as a generator, covered properly in lesson 3. For now, note that yield hands out one value at a time and the object became iterable in six lines.
Where this is genuinely useful:
class Playlist {
#tracks = [];
add(track) {
this.#tracks.push(track);
return this;
}
*[Symbol.iterator]() {
for (const track of this.#tracks) {
yield track;
}
}
}
const playlist = new Playlist().add("One").add("Two");
for (const track of playlist) {
console.log(track);
}
The #tracks array stays private, as in Unit 3, and callers still get to loop over the playlist. They cannot reach in and modify the array, which a public tracks property would have allowed.
When a class wraps a collection, giving it Symbol.iterator is almost always worth the four lines. It lets callers use the syntax they already know instead of learning playlist.getTracks(), and it keeps your internal array private, which the getter alternative does not.
EXERCISE
3What Is Already Iterable, and What Is Not
Knowing which built-in types implement the protocol explains a set of errors that otherwise look unrelated.
A quick inventory, because most confusion here is not conceptual. It is not knowing which side a given value falls on.
Iterable out of the box:
[..."hello"]; // [ 'h','e','l','l','o' ]
[...new Set([1, 2, 2, 3])]; // [ 1, 2, 3 ]
[...new Map([["a", 1]])]; // [ [ 'a', 1 ] ]
[...document.querySelectorAll("li")]; // a real array of elements
function f() {
console.log([...arguments]); // arguments is iterable
}
Strings iterate by character, a Map by [key, value] pairs, a Set by value. NodeList and arguments are array-like and iterable, which is why spread works on them even though array methods do not.
Not iterable:
// [...{ a: 1 }];
// TypeError: {} is not iterable
// [...42];
// TypeError: 42 is not iterable
// const nodes = { 0: "a", 1: "b", length: 2 };
// [...nodes];
// TypeError: nodes is not iterable
That last one is the interesting case. It is array-like: it has numeric keys and a length. But array-like and iterable are different things, and spread requires the second.
Which is exactly the difference between the two conversion functions:
const arrayLike = { 0: "a", 1: "b", length: 2 };
console.log(Array.from(arrayLike)); // [ 'a', 'b' ]
// console.log([...arrayLike]); // TypeError
const iterable = new Set(["a", "b"]);
console.log(Array.from(iterable)); // [ 'a', 'b' ]
console.log([...iterable]); // [ 'a', 'b' ]
Array.from accepts both: it uses Symbol.iterator when present and falls back to reading length and indexes when not. Spread only ever uses the iterator. So when spread fails on something that plainly has items in it, Array.from is usually the answer.
Array.from also takes a mapping function, which saves a pass:
console.log(Array.from("123", Number)); // [ 1, 2, 3 ]
console.log(Array.from({ length: 3 }, (_, i) => i)); // [ 0, 1, 2 ]
The second line is the standard way to build a range, and it works because { length: 3 } is array-like even though it holds nothing.
And a distinction worth carrying into Unit 8:
// for...in walks KEYS, including inherited ones. For objects.
// for...of walks VALUES, via Symbol.iterator. For iterables.
A one-letter difference between two loops that do unrelated things, which is why for...in over an array gives you string indexes rather than items.
