iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Iterables

An iterable is any object that defines how to produce a sequence of values. The protocol uses the special Symbol.iterator key. Everything that works with for…of and spread ... is an iterable.

The protocol

An object is iterable when it has a method at [Symbol.iterator] that returns an iterator — an object with a next() method that returns { value, done }.

JS — custom iterable
const range = {
  from: 1, to: 3,
  [Symbol.iterator]() {
    let current = this.from;
    const last  = this.to;
    return {
      next() {
        return current <= last
          ? { value: current++, done: false }
          : { value: undefined, done: true };
      },
    };
  },
};

for (const n of range) console.log(n);   // 1, 2, 3
[...range];                              // [1, 2, 3]
Array.from(range);                       // [1, 2, 3]

Generators — the easy way to make iterables

JS
function* range(from, to) {
  for (let i = from; i <= to; i++) yield i;
}

for (const n of range(1, 5)) console.log(n);   // 1..5
[...range(1, 3)];                              // [1, 2, 3]

Built-in iterables

TypeIterable?
Array, String, Set, MapYes
NodeList, HTMLCollectionYes
Generator resultsYes
Plain ObjectNo
argumentsYes
Tip: Generators are the simplest way to make a custom iterable. Use them for infinite sequences, lazy ranges, and tree walks.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Iterables!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Make a function a generator.

function range(from, to) { for (let i = from; i <= to; i++) yield i; }

Test yourself

Q1. An object is iterable if it has a method at…
Q2. Easiest way to make a custom iterable is…
Q3. Which is NOT iterable by default?

Discussion

Loading…