Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating a `GeneratorFunction` in JavaScript

Generator defined using the function* statement syntax:

// function *idMaker(){ <- also possible, even though no reference found
function* idMaker(){
  var index = 0;
  while(index < index+1)
    yield index++;
}

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

Generator defined using the function* expression syntax:

var idMaker = function*() {
   var index = 0;
   while(index < index+1)
     yield index++;
};

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

Generator defined using the GeneratorFunction constructor syntax:

var GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor;
var idMaker = new GeneratorFunction('', 'var index = 0;while(index < index+1)yield index++;');
var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

Generator function objects created with the GeneratorFunction constructor are parsed when the function is created. This is less efficient than declaring a generator function with a function* expression and calling it within your code, because such functions are parsed with the rest of the code.

Also note: Generator functions created with the GeneratorFunction constructor do not create closures to their creation contexts; they always are created in the global scope.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment