JavaScript Iterables
An iterable is any object that can be stepped through one value at a time — anything you can use in a for…of loop or spread with .... Arrays, strings, Maps, Sets, arguments, NodeLists and generator objects are all built-in iterables. You can make your own, too.
Things that consume iterables
const word = "abc";
const set = new Set([1, 2, 2, 3]);
for (const ch of word) console.log(ch);
console.log([...set]); // spread
console.log(Array.from(word)); // Array.from
const [first, second] = set; // destructuring
console.log(first, second);
console.log(Math.max(...set));
console.log(new Map(Object.entries({ x: 1, y: 2 })));a
b
c
[ 1, 2, 3 ]
[ 'a', 'b', 'c' ]
1 2
3
Map(2) { 'x' => 1, 'y' => 2 }
for…of, spread syntax, Array.from, array destructuring, new Map(), new Set() and Promise.all all accept any iterable.
The iterator protocol
Under the hood, an iterable has a method stored under the special key Symbol.iterator. Calling it returns an iterator: an object with a next() method. Each call to next() returns { value, done }:
const colors = ["red", "green"];
const it = colors[Symbol.iterator]();
console.log(it.next());
console.log(it.next());
console.log(it.next());{ value: 'red', done: false }
{ value: 'green', done: false }
{ value: undefined, done: true }
That is exactly what for…of does for you: get the iterator, call next() until done is true.
Making your own iterable
Give an object a [Symbol.iterator]() method that returns an iterator. Here's a range object that counts from from to to:
function range(from, to, step = 1) {
return {
[Symbol.iterator]() {
let current = from;
return {
next() {
if (current <= to) {
const value = current;
current += step;
return { value, done: false };
}
return { value: undefined, done: true };
},
};
},
};
}
for (const n of range(1, 5)) console.log(n);
console.log([...range(0, 20, 5)]);1
2
3
4
5
[ 0, 5, 10, 15, 20 ]
The easy way: generators
Writing next() by hand is verbose. A generator function (function*) creates an iterator automatically — each yield produces the next value. The Generators chapter goes deeper; here's the same range:
function* range(from, to, step = 1) {
for (let n = from; n <= to; n += step) yield n;
}
console.log([...range(1, 10, 3)]);
class Playlist {
constructor(...songs) {
this.songs = songs;
}
*[Symbol.iterator]() {
for (const song of this.songs) yield `♪ ${song}`;
}
}
for (const track of new Playlist("Intro", "Theme", "Outro")) console.log(track);[ 1, 4, 7, 10 ]
♪ Intro
♪ Theme
♪ Outro
Lazy and infinite sequences
Iterators produce values on demand, so a sequence can even be infinite — you only take what you need:
function* naturals() {
let n = 1;
while (true) yield n++;
}
const firstSquares = [];
for (const n of naturals()) {
if (n > 5) break;
firstSquares.push(n * n);
}
console.log(firstSquares);[ 1, 4, 9, 16, 25 ]
Note: Never spread an infinite iterator (
[...naturals()]) — it would run forever.
Built-in iterables at a glance
| Iterable | Yields |
|---|---|
| Array | elements (.keys(), .values(), .entries() also available) |
| String | characters (Unicode-aware) |
| Map | [key, value] pairs |
| Set | values |
arguments, NodeList |
elements |
| Generator object | each yielded value |
Plain objects are not iterable — use Object.entries(obj) to get an iterable array.
Test yourself
What makes an object iterable?
- A length property
- A method under the key Symbol.iterator
- Being created with new
- Having numeric keys
What does an iterator's next() return when it is finished?
- null
- undefined
- { value: undefined, done: true }
- It throws an error
Which of these is NOT iterable by default?
- "text"
- new Set()
- { a: 1 }
- [1, 2]