📘yield*
the "done" value of the iterator
JS ⟩ objects ⟩ built-in ⟩ Generator ⟩ generator function ⟩ yield* expression
the value of yield* expression is the "done" value of the iterator. (undefined by default)
replit:value of yield* expression
const { log } = console;
// generator: a()
function* a() {
yield* [1, 2, 3];
return 'foo'; // ⭐️ "done" value of `a`
}
// generator: b()
function* b() {
// --------------------------------------------------------------
const value = yield* a(); // ⭐️ "done" value of `a` returned
// after it's finished yielding.
// --------------------------------------------------------------
console.log(value) // console: 'foo'
return value + value; // ⭐️ "done" value of `b`
}
// (iterable) iterators
const it1 = a();
log(it1.next()); // {value: 1, done: false}
log(it1.next()); // {value: 2, done: false}
log(it1.next()); // {value: 3, done: false}
log(it1.next()); // {value: 'foo'⭐️, done: true}
log(it1.next()); // {value: undefined❗, done: true}
// ⭐️ "done" value is only used once❗
const it2 = b();
log(it2.next()); // {value: 1, done: false}
log(it2.next()); // {value: 2, done: false}
log(it2.next()); // {value: 3, done: false}
log(it2.next()); // console: 'foo' <--- ⭐️ "done" value of `a` returned here
// {value: 'foofoo'⭐️, done: true}
yield* is an expression (not a statement) that evaluates to a value.
yield and yield* operator can only be used within generator functions❗️
// this seems like a generator function, but there's a catch ...
function* sequence(...iterables) {
// --------------------------------------------------------------
// ⭐ `yield/yield*` only available within generator functions❗
// --------------------------------------------------------------
// ❌ but this `yield*` is within an "arrow function"❗
//
// ╭─── 🔸 arrow function ───╮
iterables.forEach( iterable => yield* iterable );
// ^^^^^^
// ⛔ ReferenceError: yield is not defined
}
Last updated