Skip to content
Home » Program to Generate a Range of Numbers in JavaScript

Program to Generate a Range of Numbers in JavaScript

In this blog post, we will learn about a JavaScript code snippet that allows us to generate a range of numbers. This code snippet is useful when we want to create an array of numbers with a specific range and step size. By using this program, we can easily generate a range of numbers without having to manually write each number. Let’s dive into the details of the code and its usage.

Code

const range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

range(0, 9, 2);
//=> [0, 2, 4, 6, 8]

// can also assign range function as static method in Array class (but not recommended )
Array.range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

Array.range(2, 10, 2);
//=> [2, 4, 6, 8, 10]

Array.range(0, 10, 1);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array.range(2, 10, -1);
//=> []

Array.range(3, 0, -1);
//=> [3, 2, 1, 0]

Code Explanation

The code snippet provides a function called range which takes three parameters: from, to, and step. This function utilizes the spread operator ... and the map method to generate the desired range of numbers.

Here’s an example usage of the range function:

javascript
const range = (from, to, step) =>
  [...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);

range(0, 9, 2);
//=> [0, 2, 4, 6, 8]

In this example, we pass 0 as the starting point, 9 as the ending point, and 2 as the step size. The function then generates an array [0, 2, 4, 6, 8], which contains all the numbers within the specified range.

Additionally, the code snippet shows an alternative approach by assigning the range function as a static method in the Array class. However, it’s worth mentioning that this approach is not recommended as it modifies the built-in JavaScript Array class.

javascript

Array.range = (from, to, step) =>

[…Array(Math.floor((to – from) / step) + 1)].map((_, i) => from + i * step);

Array.range(2, 10, 2);

//=> [2, 4, 6, 8, 10]

Array.range(0, 10, 1);

//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array.range(2, 10, -1);

//=> []

Array.range(3, 0, -1);
//=> [3, 2, 1, 0]

Conclusion

With the provided JavaScript code snippet, we can easily generate a range of numbers based on our requirements. This program is helpful when working with arrays or when we need to loop through a specific range of numbers. By using the `range` function, we can save time and effort in manually writing out each number in the range. Remember to use the code responsibly and avoid modifying built-in JavaScript objects unless necessary. Stay tuned for more helpful code snippets and programming tips!

Also checkout the following codes.


How to Use the Range Class to Generate Sequential Elements in JavaScript
Program to Generate a Range of Numbers with Step and Starting Value