JavaScript function*

Beginner
6 min read
Updated: Nov 2026

Definition and Usage

A function* declaration creates a generator function. Calling it returns a generator object. Each yield pauses and produces a value; next() or for...of resumes it.

JavaScript Syntax

JavaScript
function* count() {
  yield 1;
  yield 2;
}
console.log([...count()].join(","));
Try it Editor

How It Works

  1. function*. Declares a generator.
  2. yield. Produces values one at a time.
  3. Spread. Consumes the generator into an array.

Examples

Example 1 — Using next()

Manual stepping.

JavaScript
function* g() { yield "a"; yield "b"; }
const it = g();
console.log(it.next().value);
console.log(it.next().value);
Try it Editor

How It Works

  1. g() returns an iterator.
  2. Each next() runs to the next yield.

Example 2 — for...of

Iterate yields.

JavaScript
function* g() { yield 10; yield 20; }
for (const n of g()) console.log(n);
Try it Editor

How It Works

  1. for...of calls next() until done.

Example 3 — yield*

Delegate to another iterable.

JavaScript
function* inner() { yield 1; }
function* outer() { yield* inner(); yield 2; }
console.log([...outer()].join(","));
Try it Editor

How It Works

  1. yield* forwards values from inner.

Frequently Asked Questions

A generator object (an iterator), not the yielded values themselves.
See the Operators yield page for yield and yield*.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

6 people found this page helpful