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

Estimated read time 2 min read

To create an array from a range of numbers in JavaScript, you can use the same approach as creating an array from a range of two numbers, but you can make the function more flexible by allowing for a step or increment value. This means you can specify the amount by which to increase or decrease the number in each iteration of the loop.

Here’s an example code snippet that demonstrates how to create an array from a range of numbers in JavaScript with an optional step parameter:

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

  if (step > 0) {
    for (let i = start; i <= end; i += step) {
      rangeArray.push(i);
    }
  } else {
    for (let i = start; i >= end; i += step) {
      rangeArray.push(i);
    }
  }

  return rangeArray;
}

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

const newArray2 = createRangeArray(10, 1, -2);
console.log(newArray2); // [10, 8, 6, 4, 2]

In this code, the createRangeArray() function takes three arguments: start, end, and an optional step value which defaults to 1.

Inside the function, an empty array called rangeArray is declared. Then, an if-else statement is used to check if the step value is positive or negative. If it’s positive, a for loop is used to iterate from the start number to the end number with the specified step. In each iteration, the loop pushes the current number into the rangeArray. If step is negative, the loop decrements i by step until it reaches end.

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

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply