Skip to content

OutputNot attempted

two-way communication with yield

function* gen() {
const a = yield 1;
const b = yield a + 2;
return b + 3;
}
const g = gen();
console.log(g.next());
console.log(g.next(5));
console.log(g.next(10));
console.log(g.next());

Spaces and quote style don’t matter · write a thrown error as TypeError

Ctrl Enter
Show answer & explanation

The expected output comes from actually running the snippet; opening this shows it next to the explanation.

next(5) resumes the first yield with a = 5, so the next yield is 7. next(10) sets b = 10 and hits return 13, which produces done: true. Once finished, a generator only returns { value: undefined, done: true }.