Sikau

Advanced JavaScript · Day 14 · about 25 min

Generators

Functions that pause and resume.

Iterators the easy way

Writing next() by hand is fiddly. A generator function (with an asterisk) can pause at each yield and pick up where it left off — and it's automatically an iterator.

function* and yield

function* steps() {
  yield "Boil water";
  yield "Add tea";
  yield "Pour";
}

const it = steps();
console.log(it.next().value);
console.log([...it]);

function* range(from, to) {
  for (let n = from; n <= to; n++) yield n;
}
console.log([...range(1, 5)]);
function* ids() {
  let id = 1;
  while (true) yield id++;
}

const nextId = ids();
console.log(nextId.next().value, nextId.next().value, nextId.next().value);

The rest of this lesson

  • Pausing and resumingexplain
  • Predict the outputpredict
  • Yield values onlypredict
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript