JavaScript – range function
In this post, we will see how we can create range functions in JS.
Get Harish Krishnan’s stories in your inbox
Join Medium for free to get updates from this writer.
Method 1 — We can create an iterator using Symbol.iterator and achieve it. Let us see how to do that
function range(from, to) {
let curr = from;
const iterable = {};
iterable[Symbol.iterator] = () => {
return {
next: () => {
const currVal = curr;
++curr;
return {
done: currVal > to,
value: currVal
};
}
};
};
return iterable;
}As we can see in the above example, we create an empty object called iterable and we use [Symbol.iterator] to return an iterable. This iterable can be used in loops, spread operators, etc. For example,
console.log(...range(5, 10));Method 2— In this method we make use of the generator function which simplifies the code a lot as shown below
function * range (from, to) {
for (let curr = from; curr <= to; ++curr) {
yield curr;
}
}Please note the * beside the function keyword that signifies this is a generator function. We use the yield keyword to return the current value in the range. This works similarly to method 1.
One caveat in both the methods is that if we pass null or undefined as parameters then functions will not work as they are not iterable. In case you need to make it work please update the code as you see fit.
I also take courses on Udemy. In case you like to get course updates please join the below email list or check out my Udemy Instructor profile.








