Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Last active July 23, 2019 10:08
Show Gist options
  • Save eyecatchup/4094d7b2a69cc55dd9958ff5da706bf8 to your computer and use it in GitHub Desktop.
Save eyecatchup/4094d7b2a69cc55dd9958ff5da706bf8 to your computer and use it in GitHub Desktop.
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