Sobes.tech
Middle+

What are generators?

sobes.tech AI

Answer from AI

Generators in JavaScript are functions that can be paused and resumed, allowing them to produce values sequentially upon request. They are declared using function* and use the yield keyword to return values.

Main features of generators:

  • Enable creating lazy sequences of data.
  • Manage the state of the function between calls.
  • Can be used for asynchronous programming (together with yield and promises).

Example of a generator that yields numbers from 1 to 3:

function* numbers() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = numbers();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }

Generators are useful for working with data streams, iterators, and asynchronous code.