How to Create an Array from a Range of Two Numbers in JavaScript?

Estimated read time 2 min read

To create an array from a range of two numbers in JavaScript, you can use a loop to iterate from the starting number to the ending number and push each number into a new array. Here’s an example code snippet that demonstrates how to create an array from a range of two numbers in JavaScript:

function createRangeArray(start, end) {
  const rangeArray = [];

  for (let i = start; i <= end; i++) {

  return rangeArray;

const newArray = createRangeArray(1, 5);
console.log(newArray); // [1, 2, 3, 4, 5]

In this code, the createRangeArray() function takes two arguments: start and end which represent the starting and ending numbers of the range, respectively. Inside the function, an empty array called rangeArray is declared.

Then a for loop is used to iterate from the start number to the end number. In each iteration, the loop pushes the current number into the rangeArray.

Finally, the rangeArray is returned from the function, and its value is assigned to a new variable called newArray. We have passed the arguments 1 and 5 to the createRangeArray() function to create an array from the range of numbers between 1 and 5, and then we log the resulting array to the console.

Note that the createRangeArray() function can be modified to handle cases where the starting number is greater than the ending number or when negative numbers are involved.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply