DEV Community

Ibrahim
Ibrahim

Posted on

How to Generate an Array of Numbers in a Specific Range in JavaScript

To generate an array of numbers in a specific range using JavaScript, you can use the Array.from static method. For example:

const numbers = Array.from({ length: 5 }, (value, index) => index + 1)
console.log(numbers) // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

If you want the array to start from a different number, simply change index + 1 to the desired starting value. For example:

const numbers = Array.from({ length: 5 }, (value, index) => index + 3)
console.log(numbers) // [3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

Explanation

Array.from is a static method used to create a new array from an array-like or iterable object.

In the previous example, { length: 5 } is an array-like object used to define the length of the resulting array.

By default, the generated array will have every element value set to undefined.

To fill the array with a range of numbers, the generated array is mapped using the second argument of the Array.from method. Each element is filled with index + 1 to start the range from 1, or index + 3 to start from 3.

Top comments (1)

Collapse
 
devops_fundamental profile image
DevOps Fundamental

Insightful and well-written as always!