How to Create a Generator Method in a JavaScript Class?

Find out how to create a generator class method in JavaScript

You can create a generator class method in a JavaScript by adding * (asterisk) before the method name (separated by a space), for example, like so:

* generatorMethod();

This is slightly different from creating a generator function, where you would add the * (asterisk) right after the function keyword (i.e. function*), as JavaScript class methods don't use the "function" keyword in the method signature.

For example:

class Foo {
    * getValues() {
        yield 'foo';
        yield 'bar';
        yield* [1, 2, 3];
        // ...
    }
}

You can use it in the following way:

const foo = new Foo();
const values = foo.getValues();

console.log(values.next()); // {value: 'foo', done: false}
console.log(values.next()); // {value: 'bar', done: false}
console.log(values.next()); // {value: 1, done: false}
console.log(values.next()); // {value: 2, done: false}
console.log(values.next()); // {value: 3, done: false}
console.log(values.next()); // {value: undefined, done: true}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.