The Generator object is returned by a generator function and it conforms
to both the iterable protocol and the iterator protocol.
Syntax
function* gen() {
yield 1;
yield 2;
yield 3;
var g = gen(); // "Generator { }"
Methods
[Link]()
Returns a value yielded by the yield expression.
[Link]()
Returns the given value and finishes the generator.
[Link]()
Throws an error to a generator.
Example
An infinite iterator
function* idMaker() {
var index = 0;
while(true)
yield index++;
}
var gen = idMaker(); // "Generator { }"
[Link]([Link]().value); // 0
[Link]([Link]().value); // 1
[Link]([Link]().value); // 2
// ...
Legacy generator objects
Firefox (SpiderMonkey) also implements an earlier version of generators
in JavaScript 1.7, where the star (*) in the function declaration was not
necessary (you just use the yieldkeyword in the function body).
However, legacy generators are deprecated. Do not use them; they are
going to be removed (bug 1083482).
Legacy generator methods
[Link]()
Returns a value yielded by the yield expression. This corresponds
to next() in the ES2015 generator object.
[Link]()
Closes the generator, so that when
calling next() an StopIteration error will be thrown. This
corresponds to the return() method in the ES2015 generator object.
[Link]()
Used to send a value to a generator. The value is returned from
the yield expression, and returns a value yielded by the
next yield expression. send(x) corresponds to next(x) in the
ES2015 generator object.
[Link]()
Throws an error to a generator. This corresponds to
the throw() method in the ES2015 generator object.
Legacy generator example
function fibonacci() {
var a = yield 1;
yield a * 2;
}
var it = fibonacci();
[Link](it); // "Generator { }"
[Link]([Link]()); // 1
[Link]([Link](10)); // 20
[Link]([Link]()); // undefined
[Link]([Link]()); // throws StopIteration (as the
generator is now c