What is the output of the following? “`js const gen = function*() { const x = yield 1; const y = yield x + 2; return y; }; const g = gen(); console.log(g.next().value); console.log(g.next(10).value); console.log(g.next(20).value); “`

JavaScript Professional Medium

JavaScript Professional — Medium

What is the output of the following? “`js const gen = function*() { const x = yield 1; const y = yield x + 2; return y; }; const g = gen(); console.log(g.next().value); console.log(g.next(10).value); console.log(g.next(20).value); “`

Key points

  • Passing arguments to the `next()` method affects the yield value
  • The first `next()` call starts the generator
  • Each `next()` call resumes the generator from the last yield
  • The value returned by `next()` is accessed using `.value`
  • The `return` statement in the generator ends the iteration

Ready to go further?

Related questions