CodeBlanks Logo Icon CodeBlanks

Generator functions

JavaScript course · Advanced · Lesson 48/100

Learn to define a generator with function* and the generator object.

Generator functions

A generator is a special function that, instead of producing all values at once, yields them one by one as the caller requests. You define it with the function* syntax; the asterisk marks it as a generator rather than a regular function.

function* counter() {
  yield 1;
}
const gen = counter();

Calling a generator does not run its code right away. Instead, it returns a generator object that holds the execution state. You use this object to pull values one at a time.

function* versus a regular function

A regular function runs its body immediately and returns a value. A generator, when called, does not run its body; it returns a generator object instead. The code runs step by step only when .next() is called.

function* greeter() {
  yield 'hello';
}
const g = greeter();
g.next(); // { value: 'hello', done: false }

This lazy behavior saves memory with large or infinite sequences.

Exercise Write your first generator

Write a generator function named counter with a yield 1 expression inside. Create a generator object called gen. Call console.log(gen.next()) to log the result.

Show example solution
function* counter() {
  yield 1;
}
const gen = counter();
console.log(gen.next());

Test yourself

  1. Which is a valid generator function definition?

    • function counter*() {}
    • function generator counter() {}
    • function* counter() {}
    • generator function counter() {}
    Show answer

    function* counter() {} — Correct! The function* syntax is the standard way to define a generator.

  2. Create the generator object

    function* counter() { yield 1; }
    const gen = ____;
    Show answer
    function* counter() { yield 1; }
    const gen = counter();
  3. Match the generator concepts

    function*
    defines a generator
    generator object
    returns next()
    lazy
    runs when called

All lessons in Advanced