Javascript

How do you iterate over a range in JavaScript?1 min read

Programming languages like Rust or Python have built-in support for ranges. In JavaScript, we can use similar patterns with the help of a generator function.

To iterate over a range in JavaScript a generator function can be created that yields one value per step for the requested range:

function* range(from, to, step = 1) {
let value = from;
while (value <= to) {
yield value;
value += step;
}
}

Iterate from 1 to 3:

for (const value of range(1, 3)) {
console.log(value);
}

/*
Output:
1
2
3
*/

Iterate from 0 to 4 in 2 step increments:

for (const value of range(0, 4, 2)) {
console.log(value);
}

/*
Output:
0
2
4
*/

How does it work?

Generator functions are functions with memory that are declared as ordinary functions, but with an extra * after the function keyword:

function* name(arg1, arg2) {
yield 123;
}

Running a generator function will return a Generator object with a .next() method. The .next() method will make the generator run until the next yield statement, at which point it returns the next value wrapped in an object.

The yield statement is used instead of return to return values in generator functions. The yielded value is an object with the structure:

{
value: 123,
done: false
}

Running .next() on a generator that has reached the last yield statement will instead return:

{
value: undefined,
done: true
}

The neat thing here is that loops can use generators as iterators out of the box. This makes it easy to create all sorts of custom iterators with very little effort.

What will you create with this? Let’s go and iterate on the generators!

Pin It on Pinterest

Generated by Feedzy