Create a generator with the generator function

Generator function is a new stuff introduces in ECMAScript6. The generator function will return many values one by one and in this example we will create a generator function and then get the generator object which can then be used to return those values within the generator function.

function* generator_function() {
	yield 1; // the function uses yield keyword to store it's values.
	yield 2;
	yield 3;
}

let generator = generator_function();

console.log(generator.next().value);
console.log(generator.next().value);
console.log(generator.next().value);
console.log(generator.next().done);

The outcome is as follow:

1
2
3
true

Take note that if there is no more value lefts to return then the function will return undefined and if you are at the last value you can check the done property of that generator object to see whether is it true (no more value to return) or false.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of