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(; // {value: 'foo', done: false}
console.log(; // {value: 'bar', done: false}
console.log(; // {value: 1, done: false}
console.log(; // {value: 2, done: false}
console.log(; // {value: 3, done: false}
console.log(; // {value: undefined, done: true}

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