yield*

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.

yield*は別のジェネレーターや反復可能なオブジェクトに委任するために使用されます。

試してみましょう

function* func1() {
  yield 42;
}

function* func2() {
  yield* func1();
}

const iterator = func2();

console.log(iterator.next().value);
// Expected output: 42

構文

js
yield* expression;
expression

反復可能なオブジェクトを返す式。

解説

yield* 式はオペランドを反復し、それによって返されたそれぞれの値をもたらします。

yield* 式自体の値は、イテレーターが閉じたとき(つまり donetrue のとき)に返される値です。

別のジェネレータに委任する

次のコードでは、 g1() によってもたらされる値は、 g2() で得られているものと同じように next() の呼び出しから返されます。

js
function* g1() {
  yield 2;
  yield 3;
  yield 4;
}

function* g2() {
  yield 1;
  yield* g1();
  yield 5;
}

const 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}

他の反復可能なオブジェクト

ジェネレータオブジェクトのほかに、 yield* は他の種類の反復 (例えば、配列、文字列、 arguments オブジェクト) を yield することができます。

js
function* g3() {
  yield* [1, 2];
  yield* "34";
  yield* Array.from(arguments);
}

const 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* 式自体の値

yield* は式であり、文ではありません。そのため、値に評価されます。

js
function* g4() {
  yield* [1, 2, 3];
  return "foo";
}

function* g5() {
  const g4ReturnValue = yield* g4();
  console.log(g4ReturnValue); // 'foo'
  return g4ReturnValue;
}

const 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} done is false because g5 generator isn't finished, only g4
console.log(iterator.next()); // {value: 'foo', done: true}

仕様書

Specification
ECMAScript® 2025 Language Specification
# sec-generator-function-definitions-runtime-semantics-evaluation

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
yield*

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
See implementation notes.

関連情報