JavaScript Iterables

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.

4 min read Level 3/5 #iterables#protocol#spread
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 (from document.querySelectorAll)

If something is iterable, it works with all of these:

  • for..of loops”
  • Spread (...)
  • Destructuring
  • Array.from
  • Promise.all / Promise.race (and friends)

Spread

The ... syntax expands an iterable into individual values.

Spread into an array literal script.js
const a = [1, 2, 3];
const b = [0, ...a, 4];
console.log(b);  // [0, 1, 2, 3, 4]
▶ Preview: console

Spread also works on strings (they’re iterable):

Spread a string script.js
const chars = [..."hello"];
console.log(chars);  // ["h", "e", "l", "l", "o"]
▶ Preview: console

And on Set / Map:

Spread a Set script.js
const unique = new Set(["a", "b", "a", "c"]);
const arr = [...unique];
console.log(arr);  // ["a", "b", "c"]
▶ Preview: console

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.

Array.from script.js
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]
▶ Preview: console

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.)

A simple counter iterable script.js
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
▶ Preview: console

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 →