ES6 introduced the new for...of construct to iterate over collections:
// For...of will give us the items instead of the indexes.
for (var item of [2,4,6,8])
console.log(item)
With iterators, your own custom collections can define how they behave in for...of. Simply assign an iterator method to a property with the global iterator symbol:
var cart =
{
items: ["pizza", "car", "pastrami"],
[Symbol.iterator] : function ()
{
var index = 0;
var length = this.items.length;
return {
next: () =>
{
if (index < length)
return { value: this.items[index++], done: false };
return { value:null, done: true };
}
}
}
}
for (item of cart)
console.log(item + " is in your cart!");
Generators allow you to write the same code in a much less verbose way:
var cart =
{
items: ["pizza", "car", "pastrami"],
[Symbol.iterator] : function* ()
{
for (var index = 0; index < this.items.length; ++index)
yield this.items[index];
}
}
for (item of cart)
console.log(item + " is in your cart!");
Learn more about iterators here: https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
Leran more about generators here: https://hacks.mozilla.org/2015/05/es6-in-depth-generators/