Sub topic 7
What You Can Loop Over: Arrays, Strings, Maps, Sets and More
The previous chapter introduced the for...of syntax. This chapter covers what you can put on the right-hand side of of. JavaScript ships with several built-in iterable types. Each one decides what values it produces and in what order. Once you know these rules, you can predict any for...of loop over a standard collection.
This chapter assumes you know let and const, object and array basics, and functions. The mechanics behind iteration (Symbol.iterator and next()) come in a later chapter. Here we only look at observable behavior.
The Built-in Iterables at a Glance
An iterable is any value that for...of can walk. The language and the browser define these common ones:
| Type | What each iteration yields | Order |
|---|---|---|
| Array | Each element value | Index 0 up to `length - 1` |
| String | Each character (by code point) | Left to right |
| Map | A `[key, value]` pair | Insertion order |
| Set | Each value | Insertion order |
| `arguments` | Each argument passed | Call order |
| Typed arrays (`Uint8Array` and others) | Each numeric element | Index order |
| NodeList (browser DOM) | Each DOM node | Document order |
| Iterators from `.keys()`, `.values()`, `.entries()` | Depends on the method | Same as the source |
| Generator objects | Each `yield`ed value | As yielded |
Plain objects, WeakMap, WeakSet, numbers, null and undefined are not iterable.
Arrays
Arrays yield their element values in index order. The loop reads length as it goes, so it visits every index from 0 to length - 1.
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
// red
// green
// blueSparse arrays yield undefined for holes
A sparse array has missing indices, called holes. for...of does not skip holes. It produces undefined for each one. This is different from forEach, which skips holes.
const sparse = [1, , 3];
for (const v of sparse) {
console.log(v);
}
// 1
// undefined
// 3
sparse.forEach(v => console.log('forEach', v));
// forEach 1
// forEach 3Strings
Strings yield one character at a time, from left to right.
for (const ch of 'hey') {
console.log(ch);
}
// h
// e
// yA "character" here means a Unicode code point. That is not always the same as one entry of str[i]. The next chapter covers what this means for emoji and other characters outside the basic range.
Map
A Map yields entries. Each entry is a two-element array, [key, value], and entries come out in the order the keys were first inserted. Map keys can be any value, including objects and functions.
const roles = new Map();
roles.set('ada', 'admin');
roles.set('alan', 'editor');
roles.set('grace', 'viewer');
for (const entry of roles) {
console.log(entry);
}
// [ 'ada', 'admin' ]
// [ 'alan', 'editor' ]
// [ 'grace', 'viewer' ]If you want only keys or only values, use the matching method. Each one returns an iterator that for...of accepts:
const stock = new Map([['apple', 4], ['pear', 0]]);
for (const fruit of stock.keys()) {
console.log(fruit);
}
// apple
// pear
for (const count of stock.values()) {
console.log(count);
}
// 4
// 0Unpacking [key, value] directly in the loop head is covered in the chapter on destructuring.
Setting an existing key again changes its value but keeps its original position:
const m = new Map([['a', 1], ['b', 2]]);
m.set('a', 99);
console.log([...m.keys()]); // [ 'a', 'b' ]Set
A Set stores unique values and yields them in insertion order. Adding a value that is already there does nothing, so duplicates never appear in the loop.
const tags = new Set(['js', 'web', 'js', 'node']);
for (const tag of tags) {
console.log(tag);
}
// js
// web
// nodeThis makes Set with for...of a short way to loop over the distinct values of an array:
const visits = ['home', 'about', 'home', 'blog', 'about'];
for (const page of new Set(visits)) {
console.log(page);
}
// home
// about
// blogThe arguments Object
Inside a regular (non-arrow) function, arguments is an array-like object holding the passed values. It is iterable, even though it is not an array.
function total() {
let sum = 0;
for (const n of arguments) {
sum += n;
}
return sum;
}
console.log(total(1, 2, 3)); // 6Arrow functions have no arguments of their own. In modern code, rest parameters (...nums) give you a real array and are usually clearer.
Typed Arrays
Typed arrays such as Uint8Array and Float64Array iterate like regular arrays and yield numbers.
const bytes = new Uint8Array([72, 105]);
for (const b of bytes) {
console.log(b);
}
// 72
// 105NodeList in the Browser
document.querySelectorAll returns a NodeList, which is iterable in all current browsers. You can loop over the matched elements without converting them to an array first. This snippet runs in a browser page, not in Node.js.
for (const link of document.querySelectorAll('a')) {
console.log(link.href);
}HTMLCollection, returned by getElementsByTagName and children, is also iterable in modern browsers. Keep in mind that it is live: it updates when the DOM changes, and that can surprise you during a loop.
Iterators Are Single-Use
.keys(), .values() and .entries() return iterators. An iterator remembers its position and does not rewind. Once you loop through one, a second loop over the same iterator gets nothing.
const m = new Map([['x', 1], ['y', 2]]);
const keys = m.keys();
for (const k of keys) console.log('first', k);
// first x
// first y
for (const k of keys) console.log('second', k);
// (nothing printed)The collection itself is reusable. Each for...of over m starts fresh, because the loop asks the Map for a new iterator. Generator objects behave like stored iterators and are also single-use.
What Is Not Iterable
Passing a non-iterable to for...of throws a TypeError before the loop body runs even once:
const config = { debug: true };
try {
for (const v of config) {}
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // e.g. "config is not iterable"
}The same applies to numbers, null, undefined, WeakMap and WeakSet. Weak collections cannot be iterated by design, because their entries can be garbage-collected at any time.
To check whether a value is iterable before you loop, test for the Symbol.iterator method:
const isIterable = value =>
value != null && typeof value[Symbol.iterator] === 'function';
console.log(isIterable([1, 2])); // true
console.log(isIterable('abc')); // true
console.log(isIterable(new Map())); // true
console.log(isIterable({ a: 1 })); // false
console.log(isIterable(42)); // falseHow Symbol.iterator works is covered in the chapter on the iteration protocols. Looping over plain objects with Object.entries has a chapter of its own.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: x is not iterable` | Looping over a plain object | Use `Object.keys`, `Object.values` or `Object.entries` |
| Second loop prints nothing | Reusing a stored iterator or generator | Loop over the collection, or call `.keys()` again |
| Each item is an array, not a value | Looping a Map directly yields pairs | Use `.values()` or destructure |
| Unexpected `undefined` values | Sparse array holes | Filter holes or build the array without gaps |
| Loop over `arguments` fails | Used inside an arrow function | Use a regular function or rest parameters |
Exercise
What does this code print, and why? const s = new Set([3, 1, 3, 2]); s.add(1); for (const v of s) console.log(v);
Show answer
It prints 3, 1, 2 on separate lines. A Set keeps each value once and yields values in the order they were first inserted. The second 3 and the later add(1) do nothing because those values already exist.
Exercise
A function receives either an array or a Map and should log every value (for a Map, only the values, not the keys). Write it using for...of.
Show answer
function logValues(source) { const items = source instanceof Map ? source.values() : source; for (const v of items) console.log(v); } Looping a Map directly yields [key, value] pairs, so call .values() for Maps. Arrays already yield their values.
Exercise
Why does the second loop print nothing? const it = ['a', 'b'].values(); for (const x of it) console.log(x); for (const x of it) console.log(x);
Show answer
values() returns an iterator, and an iterator is single-use. The first loop runs it to the end. The second loop gets an iterator that is already finished, so it yields nothing. Looping over the array itself twice would work, because each loop requests a new iterator.