What are the Generators in JavaScript

In JavaScript, generators are a type of function that can be paused and resumed, allowing them to maintain their internal state across multiple invocations. This is achieved using the yield keyword.

Generators can be helpful for handling asynchronous operations, iterating over large data sets, or creating custom iterators.

To create a generator function, you use the function* keyword.

Here’s an example of a simple generator function.

function* simpleGenerator() {
  yield 'Hello';
  yield 'World';
}

const gen = simpleGenerator();

console.log(gen.next());
console.log(gen.next());
console.log(gen.next());

Output

{ value: 'Hello', done: false }
{ value: 'World', done: false }
{ value: undefined, done: true }

In this example, the simpleGenerator() function yields two values, ‘Hello’ and ‘World’. When you call the generator function, it returns a generator object.

You can then use the next() method on the generator object to get the next value in the sequence. When there are no more values to yield, the generator returns {value: undefined, done: true}.

You can also pass values back to the generator using the next() method:

function* counter() {
  let count = 0;
  while (true) {
    const increment = yield count;
    count += increment;
  }
}

const gen = counter();

console.log(gen.next());
console.log(gen.next(2));
console.log(gen.next(3));

Output

{ value: 0, done: false }
{ value: 2, done: false }
{ value: 5, done: false }

In this example, the counter generator maintains its internal state (the count variable) across invocations. The generator function receives a value through the yield keyword and updates the count.

Generators can be used in combination with for…of loop, Promises, and async/await to handle asynchronous code more elegantly.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.