Range generator

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

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • JavaScript Generator Functions

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

    Collection · 17 snippets

  • Date range generator

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

    JavaScript, Date · Jun 21, 2021

  • Using JavaScript generator functions for ranges

    Learn how to use JavaScript ES6 generators and iterators to iterate over ranges of numbers.

    JavaScript, Function · Jun 12, 2021

  • Repeat generator

    Creates a generator, repeating the given value indefinitely.

    JavaScript, Function · Oct 11, 2020