The yield*
expression is used to delegate to another generator
or iterable object.
yield* [[expression]];
expression
The yield*
expression iterates over the operand and yields each value returned by it.
The value of yield*
expression itself is the value returned by that iterator when it's closed (i.e., when done
is true).
In following code, values yielded by g1()
are returned from next()
calls just like those which are yielded by g2()
.
function* g1() { yield 2; yield 3; yield 4; } function* g2() { yield 1; yield* g1(); yield 5; } var iterator = g2(); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: 3, done: false} console.log(iterator.next()); // {value: 4, done: false} console.log(iterator.next()); // {value: 5, done: false} console.log(iterator.next()); // {value: undefined, done: true}
Besides generator objects, yield*
can also yield
other kinds of iterables, e.g. arrays, strings or arguments objects.
function* g3() { yield* [1, 2]; yield* '34'; yield* Array.from(arguments); } var iterator = g3(5, 6); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: "3", done: false} console.log(iterator.next()); // {value: "4", done: false} console.log(iterator.next()); // {value: 5, done: false} console.log(iterator.next()); // {value: 6, done: false} console.log(iterator.next()); // {value: undefined, done: true}
yield*
expression itselfyield*
is an expression, not a statement, so it evaluates to a value.
function* g4() { yield* [1, 2, 3]; return 'foo'; } var result; function* g5() { result = yield* g4(); } var iterator = g5(); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: 3, done: false} console.log(iterator.next()); // {value: undefined, done: true}, // g4() returned {value: 'foo', done: true} at this point console.log(result); // "foo"
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Yield' in that specification. | Standard | Initial definition. |
ECMAScript 2017 Draft (ECMA-262) The definition of 'Yield' in that specification. | Draft |
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | (Yes) | 27.0 (27.0) | ? | ? | 10 |
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | (Yes) | 27.0 (27.0) | ? | ? | 10 |
SyntaxError
: function* foo() { yield *[]; }
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*