Example 1 — Custom iterable
Implement the protocol.
JavaScript
const range = {
from: 1, to: 2,
[Symbol.iterator]() {
let n = this.from;
const last = this.to;
return {
next() {
if (n <= last) return { value: n++, done: false };
return { value: undefined, done: true };
}
};
}
};
console.log([...range].join(","));How It Works
- Symbol.iterator returns next().
- Spread consumes it.
