Generator

A special function that uses the yield or yield* keywords to define an iterator. When invoked a generator returns an iterator.


function* naturalNumbers() {
  let n = 1;
  while (true) {
    yield n;
    n++;
  }
}

const generator = naturalNumbers();
generator.next();
{ value: 1, done: false }
generator.next();
{ value: 2, done: false }
function* binaryCounter(bits) {
  let val = 0;

  while (val < 2 ** bits) {
    yield val.toString(2);
    val++;
  }
}

[...binaryCounter(2)]
['00', '01', '10', '11']