0 votes
in JavaScript by
What are the different kinds of generators in Javascript?

1 Answer

0 votes
by

There are five kinds of generators,

  1. Generator function declaration:

    function* myGenFunc() {
      yield 1;
      yield 2;
      yield 3;
    }
    const genObj = myGenFunc();
  2. Generator function expressions:

    const myGenFunc = function* () {
      yield 1;
      yield 2;
      yield 3;
    };
    const genObj = myGenFunc();
  3. Generator method definitions in object literals:

    const myObj = {
      *myGeneratorMethod() {
        yield 1;
        yield 2;
        yield 3;
      },
    };
    const genObj = myObj.myGeneratorMethod();
  4. Generator method definitions in class:

    class MyClass {
      *myGeneratorMethod() {
        yield 1;
        yield 2;
        yield 3;
      }
    }
    const myObject = new MyClass();
    const genObj = myObject.myGeneratorMethod();
  5. Generator as a computed property:

    const SomeObj = {
      *[Symbol.iterator]() {
        yield 1;
        yield 2;
        yield 3;
      },
    };
    
    console.log(Array.from(SomeObj)); // [ 1, 2, 3 ]
...