Common iterables
Learn common iterables like arrays, strings, NodeList and Map.
Common iterables
Many built-in JavaScript data types are iterable. Arrays yield their elements, strings yield characters, Map yields [key, value] pairs, and Set yields its unique values. All of them carry a [Symbol.iterator] method.
In the browser, document.querySelectorAll returns a NodeList, which is also iterable. So you can traverse all matched elements with for...of. The arguments object is not iterable; in old code you use a rest parameter instead of looping it directly.
NodeList and strings in detail
When for...of runs over a string, each step gives you a single character; special characters also come as one piece. A NodeList yields DOM elements in order; it supports forEach but has no map or filter.
So to transform a NodeList, a common approach is to spread it into an array with [...nodes] and then use array methods. The spread operator also uses the iterator protocol under the hood.
Exercise Count letters in a string
Define a string called text (e.g. "hello"). Declare let count = 0. Loop over the characters of the string with for...of; on every "l" character do count++. Then log the result with console.log(count).
Show example solution
const text = "hello";
let count = 0;
for (const ch of text) {
if (ch === "l") {
count++;
}
}
console.log(count);
Test yourself
-
Which can be traversed with for...of?
- A number variable
- The null value
- A Map object
- The true value
Show answer
A Map object — Correct. A Map is iterable; for...of yields [key, value] pairs.
-
for...of over a string
const word = "hello"; for (const ch ____ word) { console.log(ch); }Show answer
const word = "hello"; for (const ch of word) { console.log(ch); } -
Built-in iterables
- Array
- Yields elements
- String
- Yields characters
- Map
- [key, value] pairs
- Set
- Unique values