The use case for this syntax over using the dot notation (Array.prototype.values()
) is in a case where you don't know what object is going to be ahead of time. If you have a function that takes an iterator and then iterate over the value, but don't know if that Object is going to have a [Iterable].prototype.values method. This could be a built-in object like String object or a custom object.
function logIterable(it) {
if (!(Symbol.iterator in Object.getPrototypeOf(it)
)) {
console.log(it, ' is not an iterable object...');
return;
}
var iterator = it[Symbol.iterator]();
for (let letter of iterator) {
console.log(letter);
}
}
logIterable(['a', 'b', 'c']);
logIterable('abc');
logIterable(123);