Your Own for..of Loop
Iterable objects are those that can be iterated over using a for..of loop. The most famous examples are Arrays and Strings. But you can make ANY object iterable.
The Symbol.iterator
For an object to be iterable, it must have a method with the Symbol.iterator key.
let range = { from: 1, to: 5 };
range[Symbol.iterator] = function() {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
}
};
};
Note
Array-likes are objects that have indices and a length, but lack array methods (like map, filter). You can turn them into a real array using Array.from(obj).