Advertisement
728x90
There are five kinds of generators,
1. Generator function declaration:
javascript
1function* myGenFunc() {
2 yield 1;
3 yield 2;
4 yield 3;
5 }
6 const genObj = myGenFunc();2. Generator function expressions:
javascript
1const myGenFunc = function* () {
2 yield 1;
3 yield 2;
4 yield 3;
5 };
6 const genObj = myGenFunc();3. Generator method definitions in object literals:
javascript
1const myObj = {
2 *myGeneratorMethod() {
3 yield 1;
4 yield 2;
5 yield 3;
6 },
7 };
8 const genObj = myObj.myGeneratorMethod();4. Generator method definitions in class:
javascript
1class MyClass {
2 *myGeneratorMethod() {
3 yield 1;
4 yield 2;
5 yield 3;
6 }
7 }
8 const myObject = new MyClass();
9 const genObj = myObject.myGeneratorMethod();5. Generator as a computed property:
javascript
1const SomeObj = {
2 *[Symbol.iterator]() {
3 yield 1;
4 yield 2;
5 yield 3;
6 },
7 };
8
9 console.log(Array.from(SomeObj)); // [ 1, 2, 3 ]Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 76
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
419of476