- In my previous post we have learn about passing parameter to ES6 Generators using next() method.
- The next() method is used for iterating over a Generators.We can also iterate the Generator using for..of loop.Each iterated object in this loop is the value of yield statement.The next() method return a object with value and done property but in for…of loop each object is the direct value.
- In this demo,”We will learn to use for..of loop to iterate a Generators and also learn to develop a method to dynamically create Generators”.
- The following code contains a FruitGenerator with some yield statement with fruit names.This FruitGenerator is then iterate using for…of loop and displayed in the browser.The following code also contains a method createGenerator() which takes an array of item as input parameters and returns a anonymous Generator function invoked self.
var FruitGenerator = function*(){
yield "Apple";
yield "Orange";
yield "Grapes";
yield "Mango";
};
var messageElement = document.getElementById("message"),
fruitList = FruitGenerator();
for(var fruit of fruitList){
var h1Element = document.createElement('h1');
h1Element.innerText = fruit;
messageElement.appendChild(h1Element);
}
var createGenerator = function(itemArray){
return function*(){
for(var item of itemArray){
yield item;
}
}();
};
var flowerArray= ["Rose","Lotus","Jasmine"],
flowerList = createGenerator(flowerArray);
for(var flower of flowerList){
var h1Element = document.createElement('h1');
h1Element.innerText = flower;
messageElement.appendChild(h1Element);
}
- The output looks like following screenshot.
- The demo output can be found in the following JSBIN link. JS Bin
- The demo code can be downloaded from the following link.

