InterviewHubPRO
Section Overview
Q494

Question 494 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

95%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

What are generator functions and how do they work?

Generator functions are special functions that can pause execution and resume later, allowing them to produce a sequence of values over time instead of computing them all at once.

javascript
 function* numberGenerator() {
   yield 1;
   yield 2;
   yield 3;
 }

 const gen = numberGenerator();
 console.log(gen.next()); // { value: 1, done: false }
 console.log(gen.next()); // { value: 2, done: false }
 console.log(gen.next()); // { value: 3, done: false }
 console.log(gen.next()); // { value: undefined, done: true }

Key features:

  1. Lazy evaluation:
javascript
    function* infiniteSequence() {
      let i = 0;
      while (true) {
        yield i++;
      }
    }
  1. Two-way communication:
javascript
    function* twoWay() {
      const x = yield 'First';
      yield `Got: ${x}`;
    }

    const gen = twoWay();
    console.log(gen.next());      // { value: 'First', done: false }
    console.log(gen.next('data')); // { value: 'Got: data', done: false }
  1. Delegating to other generators:
javascript
    function* gen1() { yield 1; yield 2; }
    function* gen2() {
      yield* gen1();
      yield 3;
    }

Practical uses: iterating large datasets, implementing custom iterators, managing async flows (though async/await is now preferred).