yield* Delegates To Inner Generators

yield* delegates iteration to another generator, forwarding next() calls and handing its return value back to the outer generator.

JavascriptData Integrity

Code

javascriptsnippet
23 lines
function* inner() {
  yield 'a';
  yield 'b';
  return 'inner-done';
}

function* outer() {
  // yield* forwards next() calls and takes the inner return value
  const result = yield* inner();
  console.log('inner returned:', result);
  yield 'c';
}

console.log([...outer()]);

// yield* accepts any iterable, so recursion flattens nested rows
function* flattenDeep(rows) {
  for (const row of rows) {
    if (Array.isArray(row)) yield* flattenDeep(row);
    else yield row;
  }
}
console.log([...flattenDeep([1, [2, [3, 4]], 5])]);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

inner returned: inner-done
[ 'a', 'b', 'c' ]
[ 1, 2, 3, 4, 5 ]

How it works

The file repeats itself only inside for (const row of rows).

Applying it

The file’s steps show up in the output as inner returned:.

Iteration is driven by for (const row of rows).

Output is labeled for readability — expect lines prefixed with inner returned:.

Statements that matter

return 'inner-done';
else yield row;

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit.