Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The function* declaration

Reference for JavaScript generator functions (function*): yield, lazy sequences, passing values into next(), yield*, and use with for...of and spread.

A generator function, written function*, does not run its body when you call it. Instead it returns a generator object, which is an iterator. Each call to next() runs the body until the next yield, hands out the yielded value, and pauses with all local variables intact.

This makes generators ideal for lazy sequences, custom iteration and step-by-step state machines.

JavaScript
function* count(max) {
  for (let i = 1; i <= max; i++) yield i;
}

Try it

JS A lazy sequence

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Infinite sequences and yield*

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
function* name(params) { statements }
const g = function* (params) { statements };
const obj = { *method() {} };
class C { *method() {} }

Return value of the call: a generator object with next(), return() and throw() methods, which is also iterable.

Usage notes

  • Nothing runs on call. The body starts at the first next(). Parameters are bound at call time.
  • yield pauses; return finishes. A return value ends the generator and gives { value, done: true }. That value is ignored by for...of and spread.
  • Two-way communication. next(x) makes the paused yield expression evaluate to x. The argument of the first next() call is ignored.
  • yield* delegates to another iterable or generator and evaluates to its return value.
  • Single use. A generator object cannot be restarted. Call the generator function again for a fresh sequence.
  • Cleanup. Breaking out of a for...of loop calls the generator's return(), running its finally blocks.
  • Arrow functions cannot be generators. There is no =>* syntax.
  • Not constructors. Generator functions cannot be called with new.
  • Memory. Because values are produced on demand, a generator can represent very large or infinite sequences with constant memory.

Browser support

Generator functions are supported by all current browsers and Node.js. Iterator helper methods on generator objects (such as map() and take()) are newer; check a compatibility table before relying on them.