Range generator

Angelos Chalaris · JavaScript, Function, Generator · Oct 11, 2020

Creates a generator, that generates all values in the given range using the given step.

  • Use a while loop to iterate from start to end, using yield to return each value and then incrementing by step.
  • Omit the third argument, step, to use a default value of 1.
const rangeGenerator = function* (start, end, step = 1) {
  let i = start;
  while (i < end) {
    yield i;
    i += step;
  }
};
for (let i of rangeGenerator(6, 10)) console.log(i);
// Logs 6, 7, 8, 9

Recommended snippets & collections

  • JavaScript generator functions are a more advanced yet very powerful JavaScript ES6 feature, which you can start using in your code right now.

  • Date range generator

    JavaScript, Date

    Creates a generator, that generates all dates in the given range using the given step.

  • Repeat generator

    JavaScript, Function

    Creates a generator, repeating the given value indefinitely.

  • Creates a generator, that keeps producing new values until the given condition is met.