The secret behind for…of
for…of works on arrays, strings, Maps and Sets — but not plain objects. Why? Because those types follow the iterable protocol: they can hand out an iterator that produces values one at a time. You can make your own.
Iterators by hand
const letters = ["a", "b"]; const it = letters[Symbol.iterator](); console.log(it.next()); console.log(it.next()); console.log(it.next());
const range = {
from: 1,
to: 4,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next: () => (current <= last ? { value: current++, done: false } : { value: undefined, done: true }),
};
},
};
for (const n of range) console.log(n);
console.log([...range]);