Favorites

JavaScript Generator Object

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Generator
JavaScript Control Abstraction · ConstructorThis object is supported by all modern browsers.
Updated 28th November 2026

A Generator is the object returned by a generator function (function*). It produces a sequence of values on demand with yield, pausing between each one.

Description

A Generator object is returned when you call a generator function, declared with function*. The function's body doesn't run straight away; each call to the generator's next() method runs it until the next yield expression, which hands back a value and pauses the function until next() is called again.

Generators are iterators, so they work with for...of, spread syntax and iterator helpers. They are a simple way to create custom sequences, including infinite ones, and to write lazy pipelines. return() ends a generator early and throw() injects an error at the paused yield. Async generators (async function*) produce values over time and are consumed with for await...of.

Generator objects are both iterators and iterables, so they can be passed anywhere an iterable is expected, but like other iterators they can only be consumed once. Each call to the generator function creates a new, independent generator. Because their bodies only run on demand, generators are memory-efficient for large or computed sequences, such as reading records one at a time.

Creating

function* name() { yield value; }

Example

function* countdown(from) {
  while (from > 0) yield from--;
  return 'Lift off!';
}

const gen = countdown(3);
console.log(gen.next());
console.log([...gen]);       // the rest of the values
console.log(gen.next());

for (const n of countdown(2)) console.log(n);

Browser Support

The following information will show you the current browser support for the Generator object. Hover over a browser icon to see the version that first introduced support for this object.

This object is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee