JavaScript · Middle · Question 27 of 75

What does a generator function do?

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

Explanation

Calling a generator doesn't run its body; it returns an object with a next() method. Each next() continues until the next yield. Generators are handy for lazy and infinite sequences and for implementing iterators.

Further reading

Problem with a question

JavaScript · Middle · question 27

Test yourself

Take the JavaScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz