Labs ICT
โญ Pro Login

Generators

Generator Functions

A generator function (declared with function*) returns a Generator object. It can pause and resume execution using yield.

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

const gen = numberGenerator();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().done);
Try it Yourself โ†’

The yield Keyword

yield pauses the generator and returns a value. The generator resumes when next() is called again.

function* countUpTo(limit) {
  let count = 1;
  while (count <= limit) {
    yield count;
    count++;
  }
}

const counter = countUpTo(3);
for (const value of counter) {
  console.log(value);
}
Try it Yourself โ†’

Passing Values to next()

You can send a value back into the generator by passing an argument to next(). It replaces the yield expression.

function* interactive() {
  const name = yield "What is your name?";
  yield "Hello, " + name;
  const age = yield "How old are you?";
  yield name + " is " + age + " years old";
}

const it = interactive();
console.log(it.next().value);
console.log(it.next("Alice").value);
console.log(it.next().value);
console.log(it.next("30").value);
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What keyword is used to pause a generator function?