๐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โ๏ธ
replit๏ผyield must be in 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