FrontendDeveloper.in

JavaScript question detail

What are the different kinds of generators

There are five kinds of generators,

  1. Generator function declaration:
function* myGenFunc() {
yield 1;
yield 2;
yield 3;
}
const genObj = myGenFunc();
  1. Generator function expressions:
const myGenFunc = function* () {
yield 1;
yield 2;
yield 3;
};
const genObj = myGenFunc();
  1. Generator method definitions in object literals:
const myObj = {
*myGeneratorMethod() {
yield 1;
yield 2;
yield 3;
},
};
const genObj = myObj.myGeneratorMethod();
  1. Generator method definitions in class:
class MyClass {
*myGeneratorMethod() {
yield 1;
yield 2;
yield 3;
}
}
const myObject = new MyClass();
const genObj = myObject.myGeneratorMethod();
  1. Generator as a computed property:
const SomeObj = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};

console.log(Array.from(SomeObj)); // [ 1, 2, 3 ]
Back to all JavaScript questions
Get LinkedIn Premium at Rs 399