JavaScript Generator

Beginner
9 min read
Updated: Nov 2026
3 examples
Iteration

Definition and Usage

A generator is a special function that can pause in the middle and continue later. You write it with function* (a star after the word function) and use the keyword yield to hand out one value and pause.

Calling a generator function does not run its code. It gives you a generator object. Every time you ask this object for the next value, the code runs until the next yield, then waits again. Because it only works when asked, a generator can describe very long, or even endless, lists of values without building them all in memory.

This page explains the idea. The Generator Methods index links the full guides for next(), return() and throw().

A generator is a function with a pause button.

yield pauses and hands out a value. next() resumes. The generator remembers its variables between pauses.

JavaScript Syntax

Write a generator, then read its values with next(), for...of and the spread operator:

JavaScript
function* greetings() {              // the star makes it a generator
  yield "Hello";                     // pause and give "Hello"
  yield "Hola";
  yield "Bonjour";
}

const gen = greetings();             // nothing runs yet

console.log(gen.next());             // { value: "Hello", done: false }
console.log(gen.next().value);       // "Hola"

for (const word of greetings()) {    // for...of calls next() for you
  console.log(word);
}

console.log([...greetings()]);       // ["Hello", "Hola", "Bonjour"]

Core Ideas

Ideas every Generator tutorial in this series builds on:

IdeaExampleRemember
function*function* numbers() { ... }Declares a generator function
Generator objectconst gen = numbers();What calling a generator function gives back; it has next(), return() and throw()
yieldyield 5;Pauses the generator and hands out a value
next()gen.next()Resumes the generator and returns { value, done }
doneresult.donefalse while more values may come, true when finished
yield*yield* otherGenerator();Hands out all values of another generator or list
Iterablefor (const x of gen)A generator works with for...of, spread and Array.from()
Lazywhile (true) { yield n++; }Values are made only when asked for

Generator Function vs Regular Function

A generator function looks like a normal function, but it behaves differently:

FeatureRegular functionGenerator function
Written withfunction name() { }function* name() { }
What a call doesRuns the whole bodyOnly creates a generator object
Values it givesOne, with returnMany, one for each yield
Can pauseNoYes, at every yield
Remembers variables between callsNo, each call starts freshYes, until it finishes

An arrow function cannot be a generator, but a method in an object or a class can: write *name() { }.

How Generators Work

Calling does not run the code

Writing const gen = countdown(3) only creates the generator object. The code inside starts running at the first next().

yield pauses, next() resumes

Each next() runs the code until it reaches a yield. The value after yield goes out, and the generator waits. The next next() continues on the next line.

The result is { value, done }

While the generator has more to give, done is false. When the code ends (or reaches return), done becomes true, and all further calls give { value: undefined, done: true }.

Loops call next() for you

for...of, the spread operator [...gen] and Array.from(gen) keep calling next() until done is true. Example 1 shows all three.

You can stop or interrupt it

return() ends a generator early and lets finally clean up. throw() sends an error into the paused generator. A generator is used once: to start again, call the generator function again.

Real-Life Uses

Generators are not needed every day, but they are very handy when values come one at a time:

UseWhat it does
Endless or very long listsProduce IDs, numbers or pages of data one at a time, without building a huge array.
Custom loopsMake your own object work with for...of by writing *[Symbol.iterator]().
Reading data step by stepProcess a large file or a list of records line by line, and stop whenever you have enough.
Step-by-step tasksDescribe a process that pauses between steps, for example a wizard or an animation.

JavaScript Examples

Three short programs. Each one prints plain text, so the output is the same in Node.js and in the browser console.

Example 1 — Write Your First Generator

A countdown generator, read in three different ways.

JavaScript
function* countdown(from) {
  for (let n = from; n > 0; n--) {
    yield n;
  }
}

const gen = countdown(3);
console.log(gen.next().value);
console.log(gen.next().value);

for (const n of countdown(3)) {
  console.log("for...of: " + n);
}

console.log("Spread: " + [...countdown(3)].join(", "));
console.log("Array.from: " + Array.from(countdown(4)).join(", "));
next() tutorial

How It Works

  1. The generator. countdown(from) has a loop that does yield n for each number. The loop pauses at every yield.
  2. By hand. gen.next().value asks for one value at a time, so two calls give 3 and 2.
  3. With helpers. A new generator is created each time. for...of, [...countdown(3)] and Array.from(...) keep calling next() until the generator is done.

Example 2 — Combine Generators with yield*

yield* hands out every value of another generator. A generator method also makes an object work with for...of.

JavaScript
function* letters() {
  yield "a";
  yield "b";
}

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

function* both() {
  yield* letters();
  yield* numbers();
  yield "end";
}

console.log([...both()].join(" "));

const playlist = {
  songs: ["Intro", "Verse", "Chorus"],

  *[Symbol.iterator]() {
    for (const song of this.songs) {
      yield song;
    }
  }
};

console.log([...playlist].join(" | "));
Methods index

How It Works

  1. Delegate. yield* letters() hands out "a" and "b" from the other generator, then yield* numbers() hands out 1 and 2. A plain yield "end" comes last.
  2. Make an object iterable. The method *[Symbol.iterator]() is a generator. JavaScript calls it whenever the object is used with for...of or spread.
  3. Use it like a list. [...playlist] collects the songs in the order they were yielded.

Example 3 — Build Lazy Sequences from Small Generators

An endless generator of numbers, plus two helpers that take and transform values. Only the values you ask for are ever made.

JavaScript
function* naturals() {
  let n = 1;

  while (true) {
    yield n;
    n++;
  }
}

function* take(count, source) {
  let taken = 0;

  if (count <= 0) {
    return;
  }

  for (const value of source) {
    yield value;
    taken++;

    if (taken === count) {
      return;
    }
  }
}

function* map(source, change) {
  for (const value of source) {
    yield change(value);
  }
}

console.log([...take(5, naturals())].join(", "));
console.log([...take(4, map(naturals(), (n) => n * n))].join(", "));
return() tutorial

How It Works

  1. An endless source. naturals() would count forever, but it only moves when asked, so it does not freeze the program.
  2. Helpers that stop. take(count, source) passes on values and returns after count of them. When it stops, JavaScript calls return() on the source generator for you.
  3. Chain them. map() squares each number. Together, take(4, map(naturals(), ...)) produces 1, 4, 9, 16 and never works out a fifth value.

Generator Methods

A generator object has three methods. Each one has its own tutorial:

MethodWhat it does
next()Run the generator to the next yield and read { value, done }. You can also send a value in.
return()Finish the generator early. Its finally blocks still run.
throw()Throw an error inside the paused generator, where it can be caught.

Full list: Generator Methods index.

Frequently Asked Questions

A generator is a function written with function* that can pause at each yield and be resumed later. Calling it returns a generator object. You read values from it with next(), a for...of loop, the spread operator or Array.from().
yield pauses the generator and hands one value to the caller. When the caller asks for the next value, the generator continues on the line after the yield, with all its variables still in place.
yield pauses and gives a value, and the generator can go on later. return ends the generator and gives a final value with done: true. Loops such as for...of use the yielded values and ignore the returned one.
An array holds all its values in memory at once. A generator makes each value only when it is asked for, so it can represent huge or endless sequences, and you can stop reading whenever you have enough.
No. When a generator is finished, it stays finished and next() keeps returning { value: undefined, done: true }. To start over, call the generator function again to create a fresh generator object.

Browse the Generator methods

Open the index for next(), return() and throw(): syntax, runnable examples, and FAQs.

Generator Methods index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

17 people found this page helpful