JavaScript iterators and generators
Why a for...of loop walks an array and a string but throws "is not iterable" on a plain object, and how to fix it: the iteration protocol, Symbol.iterator, writing an iterator by hand, generators with function* and yield, spread and destructuring, and Map and Set.
In this lesson
Here’s a fleet of three rockets, in an array. A for…of loop walks it:
const fleet = ["Kestrel", "Heron", "Osprey"];
for (const ship of fleet) {
console.log(ship);
}
// Kestrel
// Heron
// Osprey
The same kind of loop walks a string, one letter at a time:
for (const letter of "Heron") {
console.log(letter);
}
// H
// e
// r
// o
// n
Now here’s the fleet as an object, each rocket’s name with its fuel level. Same loop:
const fleet = { kestrel: 80, heron: 40, osprey: 95 };
for (const ship of fleet) {
console.log(ship);
}
// Uncaught TypeError: fleet is not iterable
An array works. A string works. An object holding three rockets doesn’t. By the end of this lesson you’ll know what the loop is looking for, why an array has it and a plain object doesn’t, and three ways to give it to your own objects, the shortest of them a generator.
The iteration protocol
A for…of loop doesn’t know what an array is. It never reads a length or an index. Whatever you hand it, it does the same two things:
- It asks the value for an iterator: an object whose one job is to hand out items one at a time.
- It calls the iterator’s
next()method over and over. Every call returns a small object with two properties:value, the next item, anddone, which says whether the items have run out.
You can do the loop’s job by hand:
const fleet = ["Kestrel", "Heron", "Osprey"];
const iterator = fleet[Symbol.iterator]();
console.log(iterator.next()); // { value: "Kestrel", done: false }
console.log(iterator.next()); // { value: "Heron", done: false }
console.log(iterator.next()); // { value: "Osprey", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
The fourth call says done: true, and that’s where a loop stops. Those two steps together are the iteration protocol. A value that can hand over an iterator is called iterable, which is the word in the error. Each request makes a fresh iterator, back at the first item, so two loops over the same array never get in each other’s way.
Symbols
Look at how we asked the array. The method that hands over the iterator isn’t kept under a name like push. Its key is Symbol.iterator, in square brackets. Every property key you’ve seen so far has been a string. This one is a symbol, a primitive type of its own:
console.log(typeof Symbol.iterator); // symbol
Call the Symbol function and you get a new symbol. No two are ever equal, even with the same description:
console.log(Symbol("checked") === Symbol("checked")); // false
console.log("checked" === "checked"); // true
The text in Symbol("checked") is only a description, for debugging. It isn’t the key. So a symbol is a key that can’t clash with any other. That’s why the language used one here: code written before 2015 could already have had a property called iterator that meant something else, and a loop that looked for that string would have picked it up by mistake.
A symbol key also stays out of the way. Object.keys doesn’t list it:
const checked = Symbol("checked");
const kestrel = { name: "Kestrel", fuel: 80 };
kestrel[checked] = true;
console.log(Object.keys(kestrel)); // ["name", "fuel"]
console.log(kestrel[checked]); // true
The key goes in square brackets because it’s a value, not a name: kestrel.checked would look for a property whose name is the string "checked".
Symbol.iterator is a symbol the language made itself and keeps on the Symbol function, so every program reaches the same one. An array doesn’t hold the method under it itself: it finds it on Array.prototype, where push and every other array method live. A string has one too. A plain object has nothing under that key, and that’s all the error means:
console.log(typeof ["Kestrel", "Heron", "Osprey"][Symbol.iterator]); // function
console.log(typeof "Heron"[Symbol.iterator]); // function
console.log(typeof { kestrel: 80, heron: 40, osprey: 95 }[Symbol.iterator]); // undefined
Looping over an object
So how do you loop over an object? Ask it for an array first. Object.keys gives you the property names, Object.values the values, and Object.entries both, as pairs:
const fleet = { kestrel: 80, heron: 40, osprey: 95 };
console.log(Object.keys(fleet)); // ["kestrel", "heron", "osprey"]
console.log(Object.values(fleet)); // [80, 40, 95]
console.log(Object.entries(fleet)); // [["kestrel", 80], ["heron", 40], ["osprey", 95]]
An array is iterable, so the loop runs. Destructuring splits each pair into a name and a fuel level:
const fleet = { kestrel: 80, heron: 40, osprey: 95 };
for (const [name, fuel] of Object.entries(fleet)) {
console.log(`${name}: ${fuel}%`);
}
// kestrel: 80%
// heron: 40%
// osprey: 95%
An object doesn’t choose between names, values and pairs for you. You say which one you want.
There’s an older loop too, for…in, which walks an object’s property names:
const fleet = { kestrel: 80, heron: 40, osprey: 95 };
for (const name in fleet) {
console.log(name);
}
// kestrel
// heron
// osprey
Point it at an array, and you get the positions, as strings, not the items:
const fleet = ["Kestrel", "Heron", "Osprey"];
for (const name in fleet) {
console.log(name, typeof name);
}
// 0 string
// 1 string
// 2 string
for…in also walks properties an object inherits. for…of never looks at property names at all: it asks for an iterator.
Writing an iterator
Or you can give the object the answer the loop is looking for. Assign a function to the fleet, under Symbol.iterator:
const fleet = { kestrel: 80, heron: 40, osprey: 95 };
fleet[Symbol.iterator] = function () {
const names = Object.keys(this);
let index = 0;
return {
next() {
if (index < names.length) {
const name = names[index];
index = index + 1;
return { value: name, done: false };
}
return { value: undefined, done: true };
},
};
};
for (const ship of fleet) {
console.log(ship);
}
// kestrel
// heron
// osprey
The loop calls the function as a method of the fleet, so inside it, this is the fleet. It collects the names with Object.keys and starts an index at zero. What it returns is the iterator: one object with a single method, next. While the index hasn’t run past the names, next returns the next name with done: false and moves the index on. After that it returns done: true. The loop we started with now runs, with no error.
Two things to notice. The iterator keeps its place between calls because next is a closure: it holds on to index after the outer function has finished. And the loop printed three names, not four, though the fleet now has a fourth property. Object.keys left it out, because its key is a symbol.
The method has to be a function, not an arrow function: an arrow function doesn’t get the fleet as this.
Generators
That took fourteen lines. A generator is a shorter way to write an iterator. Write function with a star after it, and inside, use the keyword yield. Here’s the countdown loop from earlier in this series, with one change: where it printed each number, it yields it:
function* countdown(seconds) {
while (seconds > 0) {
yield seconds;
seconds = seconds - 1;
}
}
const timer = countdown(3);
console.log(timer.next()); // { value: 3, done: false }
console.log(timer.next()); // { value: 2, done: false }
console.log(timer.next()); // { value: 1, done: false }
console.log(timer.next()); // { value: undefined, done: true }
Calling countdown(3) runs none of the body. You get back a generator object, and it’s an iterator: it has next. The first next() starts the body. At yield, it hands out 3 and pauses right there, inside the loop. The next call carries on from where it stopped: it takes one off, goes around, and yields 2. Then 1. Once more, and the loop ends, the function finishes, and you get done: true.
A generator object is iterable as well, so you can hand it straight to for…of:
function* countdown(seconds) {
while (seconds > 0) {
yield seconds;
seconds = seconds - 1;
}
}
for (const second of countdown(3)) {
console.log(second);
}
// 3
// 2
// 1
A generator object can be walked once; call countdown(3) again for a fresh one. There’s no arrow-function form of a generator.
Back to the fleet. Replace the hand-written function with a generator that loops over the names and yields each one:
const fleet = { kestrel: 80, heron: 40, osprey: 95 };
fleet[Symbol.iterator] = function* () {
for (const name of Object.keys(this)) {
yield name;
}
};
for (const ship of fleet) {
console.log(ship);
}
// kestrel
// heron
// osprey
Fourteen lines become five, and the loop prints the same three names. There’s no index to keep and no done to return: the generator keeps its place in the code itself. In a class or an object literal, the same thing is written as a method: *[Symbol.iterator]() { … }.
Only when asked
A generator runs only when something asks for the next value. So it can do what an ordinary function can’t: never finish. Here’s a duty rotation:
function* rotation(ships) {
while (true) {
for (const ship of ships) {
yield ship;
}
}
}
const onDuty = rotation(["Kestrel", "Heron", "Osprey"]);
console.log(onDuty.next().value); // Kestrel
console.log(onDuty.next().value); // Heron
console.log(onDuty.next().value); // Osprey
console.log(onDuty.next().value); // Kestrel
console.log(onDuty.next().value); // Heron
Earlier in this series, a loop whose condition never turns false meant a frozen page. This one runs one step per call. Ask five times and you get five names; the sixth is worked out only if you ask. Don’t spread this one or loop over it without a way out: [...rotation(ships)] never finishes, and runs out of memory.
A function that pauses and keeps its place may sound familiar. An async function does that at await, until a promise settles. A generator does it at yield, until you call next().
Spread and destructuring
The for…of loop isn’t the only thing that asks for an iterator. Spreading into an array calls next() until it’s done. Array destructuring does too, and stops as soon as its names are filled, so it can take the first two rockets from a rotation that never ends:
const fleet = { kestrel: 80, heron: 40, osprey: 95 };
fleet[Symbol.iterator] = function* () {
for (const name of Object.keys(this)) {
yield name;
}
};
function* rotation(ships) {
while (true) {
for (const ship of ships) {
yield ship;
}
}
}
console.log([...fleet]); // ["kestrel", "heron", "osprey"]
const [first, second] = fleet;
console.log(first, second); // kestrel heron
console.log([..."Heron"]); // ["H", "e", "r", "o", "n"]
const [a, b] = rotation(["Kestrel", "Heron", "Osprey"]);
console.log(a, b); // Kestrel Heron
That’s why both work on an array, on a string, and now on our fleet, and why both fail on a plain object with the loop’s message:
const plain = { kestrel: 80, heron: 40, osprey: 95 };
try {
console.log([...plain]);
} catch (error) {
console.log(error.message); // plain is not iterable
}
try {
const [x] = plain;
} catch (error) {
console.log(error.message); // plain is not iterable
}
One thing from the episode on modern syntax is different: three dots inside curly braces copy an object’s properties, and no iterator is involved:
const plain = { kestrel: 80, heron: 40, osprey: 95 };
console.log({ ...plain }); // { kestrel: 80, heron: 40, osprey: 95 }
Other places take any iterable too: Promise.all, new Map and new Set.
Map and Set
JavaScript has two built-in collections that are iterable from the start. The first is Map, with a capital M, not the array method. A Map holds pairs, each one a key with its value, as an object does, but it’s made to be a collection. You set a pair, get a value by its key, and it knows its size:
const fleet = new Map();
fleet.set("kestrel", 80);
fleet.set("heron", 40);
fleet.set("osprey", 95);
console.log(fleet.get("heron")); // 40
console.log(fleet.size); // 3
for (const [name, fuel] of fleet) {
console.log(`${name}: ${fuel}%`);
}
// kestrel: 80%
// heron: 40%
// osprey: 95%
A key can be any value, not only a string: an object turns every key into a string, so 1 and "1" are one key there, while a Map keeps them apart. When you loop over a Map, each round hands you a pair, in the order they went in. Read it with get, not a dot: fleet.kestrel is undefined.
The second is Set, with a capital S: a collection where each value appears once. Add Kestrel a second time, and nothing changes:
const launched = new Set();
launched.add("Kestrel");
launched.add("Heron");
launched.add("Kestrel");
console.log(launched.size); // 2
Put a list into a Set, spread it back into an array, and the duplicates are gone:
const log = ["Kestrel", "Heron", "Kestrel", "Osprey", "Heron"];
console.log([...new Set(log)]); // ["Kestrel", "Heron", "Osprey"]
Back to the fleet
The loop we started with failed because the fleet object had nothing under Symbol.iterator. You now have three ways to fix that.
For a quick loop, ask for an array, with Object.entries:
const fleet = { kestrel: 80, heron: 40, osprey: 95 };
for (const [name, fuel] of Object.entries(fleet)) {
console.log(name, fuel);
}
If the data is a collection of pairs, make it a Map:
const fleet = new Map([
["kestrel", 80],
["heron", 40],
["osprey", 95],
]);
for (const ship of fleet) {
console.log(ship);
}
// ["kestrel", 80]
// ["heron", 40]
// ["osprey", 95]
And if it’s a type of your own, give it a generator under Symbol.iterator, and loops, spread and destructuring all work on it:
const fleet = { kestrel: 80, heron: 40, osprey: 95 };
fleet[Symbol.iterator] = function* () {
for (const name of Object.keys(this)) {
yield name;
}
};
for (const ship of fleet) {
console.log(ship);
}
The loop was never about arrays. It asks one question, and any value can answer it.
Summary
- A
for…ofloop gets an iterator from a value, through the method underSymbol.iterator, then callsnext()until a result saysdone: true. That’s the iteration protocol, and a value that answers it is iterable. - Arrays, strings,
MapandSethave the method; a plain object doesn’t, which is all “is not iterable” means. Symbol.iteratoris a symbol: a key that is never equal to any other, never clashes with a string key, and isn’t listed byObject.keys.- To loop over an object, ask for an array with
Object.keys,Object.valuesorObject.entries.for…inwalks property names, and on an array gives positions as strings. - A hand-written iterator is any object with a
nextmethod; it keeps its place in a closure. - A generator,
function*withyield, writes that iterator for you: it runs to the nextyieldand pauses until the nextnext(), so it can even run forever. - Spread and array destructuring use the same protocol as the loop; object spread copies properties and doesn’t.
Mapholds pairs with keys of any type, in the order they went in;Setholds each value once.
Video transcript
Intro
Here's a fleet of three rockets, in an array. A for of loop walks it: Kestrel, Heron, Osprey. The same kind of loop walks a string, one letter at a time. Now here's the fleet as an object, each rocket's name with its fuel level. Same loop. TypeError: fleet is not iterable. An array works. A string works. An object holding three rockets doesn't. So what is the loop looking for, that an array has and an object doesn't? Today, we find out.
By the end of this video, you'll understand three things. One: the iteration protocol: what for of needs from a value, and why an array has it and a plain object doesn't. Two: iterators and symbols: how to make an object of your own work with the loop, written out by hand. Three: generators: functions that pause at the word yield, and write the iterator for you.
The iteration protocol
A for of loop doesn't know what an array is. It never reads a length or an index. Whatever you hand it, it does the same two things. First, it asks the value for an iterator. An iterator has one job: handing out items one at a time. Then it calls a method on that iterator, next, over and over. Every call hands back a small object. One of its properties is value, the next item. The other is done, which says whether the items have run out. You can do the loop's job by hand. Ask the array for its iterator. Call next: Kestrel, done false. Again: Heron. Again: Osprey. Once more: value undefined, done true, and that's where the loop stops. Those two steps are the iteration protocol. A value that can hand over an iterator is called iterable, which is the word in the error.
Symbols
Look at how we asked the array. The method that hands over the iterator isn't kept under a name, like push. Its key is Symbol dot iterator, in square brackets. Every property key in this series so far has been a string. This one is a symbol, a primitive type we haven't met. Call the Symbol function and you get a new one, and no two are ever equal, even with the same description. So a symbol is a key that can't clash. Code written before 2015 could already have a property called iterator that meant something else, and a loop that looked for that string would have picked it up by mistake. With a symbol, that can't happen. A symbol key also stays out of the way: Object dot keys doesn't list it. Symbol dot iterator is one the language made itself and keeps on the Symbol function, so every program reaches the same one. An array doesn't hold that method itself. It finds it on Array dot prototype, where push and every other array method live. A string has one too. A plain object has nothing under that key, and that's all the error means.
Looping over an object
So how do you loop over an object? Ask it for an array first. Object dot keys gives you the property names. Object dot values gives you the values. Object dot entries gives you both, as pairs, and destructuring, from the episode on modern syntax, splits each pair into a name and a fuel level. An array is iterable, so the loop runs: Kestrel, eighty percent. Heron, forty. Osprey, ninety-five. An object doesn't choose between those three for you. You say which one you want. There's an older loop too, for in, which walks an object's property names. Point it at an array, and you get the positions, as strings, not the items.
Writing an iterator
Or you can give the object the answer the loop is looking for. Assign a function to the fleet, under Symbol dot iterator. The loop calls it as a method of the fleet, so inside, this is the fleet. It collects the names with Object dot keys, and starts an index at zero. What it returns is the iterator: one object, with a single method, next. If the index hasn't run past the names, next returns that name with done false, and moves the index on. Otherwise it returns done true. Now run the loop we started with. Kestrel, Heron, Osprey, and no error. Two things to notice. The iterator keeps its place between calls because next is a closure, from the functions episode: it holds on to the index. And the loop printed three names, not four, though the fleet now has a fourth property. Object dot keys left it out, because its key is a symbol.
Generators
That took fourteen lines. JavaScript has a shorter way to write an iterator: a generator. Write function with a star after it, and inside, use the keyword yield. This is the countdown loop from early in this series, with one change: where it printed each number, it yields it. Call countdown with three, and none of that code runs yet. You get back a generator object, and it's an iterator: it has next. Call next, and the body starts. At yield, it hands out three and pauses right there, inside the loop. Call next again, and it carries on from where it stopped: it takes one off, goes around, and yields two. Then one. Call it once more: the loop ends, the function finishes, and you get done true. A generator object is iterable as well, so you can hand it straight to for of: three, two, one.
Back to the fleet. Replace the hand-written function with a generator: loop over the names, and yield each one. Fourteen lines become five, and the loop prints the same three names. There's no index to keep and no done to return. The generator keeps its place in the code itself.
Only when asked
A generator runs only when something asks for the next value. So it can do what an ordinary function can't: never finish. Here's a duty rotation. Inside while true, it loops over the ships and yields each one. Early in this series, a loop whose condition never turns false meant a frozen page. This one runs a step per call. Ask five times, and you get five names: Kestrel, Heron, Osprey, Kestrel, Heron. The sixth is worked out only if you ask. A function that pauses and keeps its place may sound familiar. An async function does that at await, until a promise settles. A generator does it at yield, until you call next.
Spread and destructuring
The for of loop isn't the only thing that asks for an iterator. The three dots do. Spreading into an array calls next until it's done. Array destructuring does too, and it stops as soon as its names are filled, so it can take the first two rockets from a rotation that never ends. That's why both work on an array, on a string, and now on our fleet, and why both fail on a plain object with the same message. One thing from the episode on modern syntax is different: three dots inside curly braces copy an object's properties, and no iterator is involved.
Map and Set
JavaScript has two built-in collections that are iterable from the start. The first is Map, with a capital M, not the array method. A Map holds pairs, each one a key with its value, as an object does, but it's made to be a collection. You set a pair, and get a value by its key. It knows its size. A key can be any value, not only a string. And when you loop over it, each round hands you a pair, in the order they went in. The second is Set, with a capital S: a collection where each value appears once. Add Kestrel a second time, and nothing changes. Put a list into a Set, spread it back into an array, and the duplicates are gone.
Back to the fleet
Which brings us back to the loop we started with. The fleet object failed because it had nothing under Symbol dot iterator. You now have three ways to fix that. For a quick loop, ask for an array, with Object dot entries. If the data is a collection of pairs, make it a Map. And if it's a type of your own, give it a generator under Symbol dot iterator, and loops, spread and destructuring all work on it. The loop was never about arrays. It asks one question, and any value can answer it.
In one line
That's iteration in one line: a for of loop gets an iterator from a value and calls next until it's done; the method that hands it over lives under a symbol, and a generator writes that method for you.
Next time
Next time, we leave the console and take JavaScript to the page: the DOM, the tree of objects a browser builds from a page, and how a script finds one element in it and changes it, with no reload.

