What Makes Something for..of-able
JavaScript Iterables
An iterable is anything that knows how to produce its values one at a time. Arrays, strings, sets, maps — and you can make your own.
What you'll learn
- Identify built-in iterables
- Use `...` spread to unpack an iterable
- Use `Array.from` to materialize an iterable
An iterable is anything that can be looped over with for..of.
JavaScript’s built-in iterables:
- Strings
- Arrays
- Sets
- Maps
- Typed arrays (
Uint8Array, etc.) - The return values of generators (later)
arguments(legacy)NodeList(fromdocument.querySelectorAll)
If something is iterable, it works with all of these:
- “
for..ofloops” - Spread (
...) - Destructuring
Array.fromPromise.all/Promise.race(and friends)
Spread
The ... syntax expands an iterable into individual values.
const a = [1, 2, 3];
const b = [0, ...a, 4];
console.log(b); // [0, 1, 2, 3, 4] Spread also works on strings (they’re iterable):
const chars = [..."hello"];
console.log(chars); // ["h", "e", "l", "l", "o"] And on Set / Map:
const unique = new Set(["a", "b", "a", "c"]);
const arr = [...unique];
console.log(arr); // ["a", "b", "c"] Array.from
Where spread builds an array literal, Array.from is a function that
takes any iterable and gives you an array. Plus, it can transform the
values on the way in.
const arr1 = Array.from("hello");
console.log(arr1); // ["h", "e", "l", "l", "o"]
const squares = Array.from([1, 2, 3, 4], (n) => n * n);
console.log(squares); // [1, 4, 9, 16]
// Like `range(0, 5)`:
const range = Array.from({ length: 5 }, (_, i) => i);
console.log(range); // [0, 1, 2, 3, 4] Making Your Own Iterable
An object becomes iterable by implementing the iterator protocol —
a method called [Symbol.iterator] that returns an object with a
next() method. (You’ll usually use a function* generator instead,
covered later.)
const upToFive = {
[Symbol.iterator]() {
let n = 0;
return {
next() {
return n < 5
? { value: n++, done: false }
: { value: undefined, done: true };
},
};
},
};
for (const x of upToFive) {
console.log(x);
}
// 0, 1, 2, 3, 4 This is mostly informational — you won’t write this often. The Generators lesson (later) shows a cleaner way.
End of Chapter
That wraps Control Flow. You can now make decisions and loop with confidence. Next chapter: the most important abstraction in JavaScript — functions.
Next chapter: Functions →