πŸ”΄ HardEvent Loop & PromisesπŸ’» Output Question

Generator two-way communication

πŸ’‘

Hint

Values passed to next(val) become the result of the yield expression β€” two-way communication. The FIRST next() can't pass a value (nothing waiting for it).

What does this output?

function* calculator() {
  const x = yield 'Enter x:';
  const y = yield 'Enter y:';
  return x + y;
}

const calc = calculator();
console.log(calc.next().value);
console.log(calc.next(10).value);
console.log(calc.next(5).value);

Correct Output

Enter x:
Enter y:
15

Why this output?

Explanation: First next(): runs to first yield, returns "Enter x:". next(10): resumes β€” 10 is the result of that first yield expression (x=10) β€” runs to second yield, returns "Enter y:". next(5): 5 becomes y, returns x+y = 15.

Key Insight: Values passed to next(val) become the result of the yield expression β€” two-way communication. The FIRST next() can't pass a value (nothing waiting for it).

More Event Loop & Promises Output Questions

🟑 MediumClassic setTimeout vs Promiseβ†’πŸ”΄ HardNested setTimeout and Promiseβ†’πŸŸ‘ Mediumasync/await execution orderβ†’πŸ”΄ HardPromise chaining orderβ†’

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz