Iterable : Object
An iterable object is any object that has a
%%/Symbol#iterator|**Symbol.iterator**%% property whose value is a
function that returns an %%/Iterator|**Iterator**%%.
You can loop over all values in an iterable object by using a
**for (const value of iterable) { }** loop.
You may create your own iterable object by assigning the
%%/Symbol#iterator|**Symbol.iterator**%% property to a
generator function (**function* () {}**) or an object with a
%%/Iterator#next|**next()**%% method.
See %%/Iterator|Iterator%% for more details.
Version:
ECMAScript 2015
Spec:
http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface
----
instance[Symbol.iterator] : Function
Returns a function that produces an Iterator for this object.
// Arrays are a built in Iterable object
const arr = ['a', 'b', 'c'];
// Use for (... of ...) loop to get the values of an iterable
for (const x of arr) {
console.log(x);
}
// Create an iterable class with a generator function
class MyIterable {
constructor(maxValue) {
this._maxValue = maxValue;
}
*[Symbol.iterator]() {
for (let i = 0; i < this._maxValue; i++) {
yield i;
}
}
}
for (const x of new MyIterable(3)) {
console.log(x);
}
// Under the covers, for (... of ...) does the following:
const iterator = arr[Symbol.iterator]();
let current = iterator.next();
while (!current.done) {
console.log(current.value);
current = iterator.next();
}