MENU
Generator
Generator functions can be paused, returned, and resumed, comparable to the StartCoroutine() function in Unity.Calling a generator function returns an iterator.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function* idMaker(){
var index = 0;
while(true) yield index++;}var gen = idMaker();console.log(gen.next().value); // 0console.log(gen.next().value); // 1console.log(gen.next().value); // 2
</script></body><html>
Arguments can be passed into the iterator.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function* logGenerator() {
console.log(yield); console.log(yield); console.log(yield);}var gen = logGenerator();gen.next(); gen.next(1); // 1gen.next(2); // 2gen.next(3); // 3
</script></body><html>
'return'prevents the generator from resuming.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function* gf() {
yield 1;
return 2;
yield 3;}var gen = gf();console.log(gen.next()); // {value: 1, done: false}console.log(gen.next()); // {value: 2, done: true}console.log(gen.next()); // {value: undefined, done: true}
</script></body><html>
To nest generators, use yield *yield * yield * instead.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function* anotherGenerator(i) {
yield i + 1;
yield i + 2;}function* generator(i) {
yield i;
yield* anotherGenerator(i);
yield i + 10;}var g = generator(10);console.log(g.next().value); // 10console.log(g.next().value); // 11console.log(g.next().value); // 12console.log(g.next().value); // 20
</script></body><html>
Generators are not constructable.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function* f() {}var obj = new f; // throws "TypeError: f is not a constructor"
</script></body><html>
To tell if a function is a generator function:
RESETRUNFULL
<!DOCTYPE html><html><body><script>
function isGenerator(fn) { return fn.constructor.name === 'GeneratorFunction';}function f(){}function* g(){}console.log(isGenerator(f)); // falseconsole.log(isGenerator(g)); // trueconsole.log(g instanceof (function*(){}).constructor); //true
</script></body><html>