Loop through a generator function in ES6

A generator function is a function which will return multiple values one by one each time we call it’s next method to get it’s value.

For example, here is a sample of the generator function…

function* helloIterator() {
    yield "hello";
    yield "world!";
}

We use the keyword yield before each value in the function and insert a ‘*’ after function.

To use the function above we first assign it to a variable…

let generator = helloIterator();

Then we can call it’s next method and get it’s value…

generator.next().value;

Each time we call the next method we can access a value until we receive an undefined value which means there is no more value which can be returned by the function!

Although the generator function is great but the step to retrieve the values within the generator function is simply too troublesome, luckily ES6 has offered the for…of loop which we can use to loop through each value in the generator function. The loop will automatically stop if there is no more value to be returned. Here is the entire code…

function* helloIterator() {
    yield "hello";
    yield "world!";
}
let greeting = "";
for (let greet of helloIterator())
	greeting += greet + " ";
console.log(greeting);

which will output

hello world! 

Imagine if there are 1000 values in the generator function, how many times do we need to call the next method? With the help of the for…of loop everything is so simple and easy now with just a few lines of code!

Phew! There are more ES6 tutorials to come so do like this post if you are into this kinda stuff!

Like this post? Kindly share!