Javascript Generator Functions

Hands-on practice for this lecture. Write the code, see it run, understand the pattern.

1

Exercise 1 of 1

Generator Functions -- Quiz

Four scenarios testing the call/yield/return/exhaust cycle: what happens when you call a generator, what .next() returns, how yield differs from return, and what an exhausted generator does.

Four scenarios, one question each. Tests whether the call/yield/return/exhaust cycle is clear.

Calling a Generator

function* doWork() {
  console.log('started');
  yield 1;
}

const gen = doWork();

1What happens on the line const gen = doWork()?

Reading .next()

function* doWork() {
  yield 42;
}

const gen = doWork();
console.log(gen.next());

2What does gen.next() log?

yield vs return

function* counter() {
  yield 1;
  yield 2;
  return 'end';
}

const gen = counter();
gen.next(); // call 1
gen.next(); // call 2
gen.next(); // call 3

3What does the third gen.next() (call 3) return?

Exhausted Generator

function* once() {
  yield 'hello';
}

const gen = once();
gen.next(); // { value: 'hello', done: false }
gen.next(); // { value: undefined, done: true }
gen.next(); // ???

4What does the third gen.next() return?

0/4 answered

Practice: Javascript Generator Functions — Interactive Exercises | Durgesh Rai