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
| Type | Iterable? |
|---|---|
| Array, String, Set, Map | Yes |
| NodeList, HTMLCollection | Yes |
| Generator results | Yes |
| Plain Object | No |
arguments | Yes |
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; }
A single character after `function`.
Discussion
Loading…