How to Create a Generator Method in a JavaScript Class?

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}

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.