Function*
What is it
function*
creates a binding of a new generator function to a given name
- Generator function can be exited and re-entered, with its context (variable bindings) saved across re-entrances
function* generator(i) { yield i; yield i + 10; } const gen = generator(10); console.log(gen.next().value); // 10 console.log(gen.next().value); // 20 console.log(gen.next().value); // undefined
A function* declaration creates a GeneratorFunction object
- Each time a generator function is called, it returns a new Generator object, which conforms to the iterator protocol
- When the iterator's
next()
method is called, the generator function's body is executed until the firstyield
expression, which specifies the value to be returned from theiterator
or, withyield*
, delegates to another generator function. - The
next()
method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. - Calling the
next()
method with an argument will resume the generator function execution, replacing the yield expression where an execution was paused with the argument fromnext()
.
function* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3; } function* generator(i) { yield i; yield* anotherGenerator(i); yield i + 10; } const gen = generator(10); console.log(gen.next().value); // 10 console.log(gen.next().value); // 11 console.log(gen.next().value); // 12 console.log(gen.next().value); // 13 console.log(gen.next().value); // 20 console.log(gen.next().value); // undefined