Iterators and Generators
For Of Iterables
Use for...of with a custom iterable.
For Of Iterables
for_of_iterable.js
const stop = 3;
const values = [];
const range = {
[Symbol.iterator]() {
let current = 1;
return {
next() {
if (current <= stop) {
const value = current;
current = current + 1;
return { value, done: false };
}
return { value: undefined, done: true };
},
};
},
};
for (const value of range) {
values.push(value * 10);
}
console.log("stop=" + stop);
console.log("scaled=" + values.join("-"));
for-of-iterable
`for...of` reads from any object that provides `Symbol.iterator`. The loop keeps asking for the next value until the iterator is done.