Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

function*

A generator function: produces values one at a time with yield.

Available since: ES2015

Syntax

function* name() { yield value; }

Examples

A generator yields values on demand:

function* count() {
  yield 1;
  yield 2;
  yield 3;
}
 
console.log([...count()].join(', '));

Output:

1, 2, 3

An infinite sequence — take only what you need:

function* ids() {
  let id = 1;
  while (true) yield id++;
}
 
const generator = ids();
 
console.log(generator.next().value);
console.log(generator.next().value);
console.log(generator.next().value);

Output:

1
2
3

Iterator helper methods:

function* naturals() {
  let n = 1;
  while (true) yield n++;
}
 
console.log(naturals().filter((n) => n % 2 === 0).map((n) => n * 10).take(3).toArray().join(', '));

Output:

20, 40, 60

Notes

A generator's code runs in pieces: each next() call runs to the next yield and pauses. That is why an infinite loop inside a generator does not freeze the program.

See also

  • Symbol.iterator — A special key that makes an object iterable in for...of and spread.
  • for...of — Loops over the values of arrays, strings, Maps, Sets and other iterables.
  • for await...of — Loops over asynchronous data sources, waiting for each item.

In the tutorial

  • Iterators and generators — How for...of works in JavaScript: iterable objects, iterators and the next method, generator functions with yield, and your own iterable object.

Thanks for reading!

Donate to the site — we work hard for you.