In this article we will see how to create a range of integers with JavaScript.
We can implement the following function:
'use strict';
function createNumberRange(start = 1, end = 10) {
return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}
The createNumberRange
function takes two parameters: start
and end
. These parameters respectively represent the start value and the end value for the range of numbers to be generated.
Within the function, the method Array.from()
is used . This method creates a new array from an iterable object or an array-like object. In our case, the iterable object is an object created using the syntax { length: end - start + 1 }
. This object has a length
property which indicates the length of the array we wish to create. The length is calculated by subtracting the value of start
from the value of end
and adding 1.
So let's move on to another part of the code: (_, i) => start + i
. This is an arrow function which is used as an optional argument of the Array.from()
method. The underscore _
represents a parameter that will not be used in the function body. The i
parameter represents the index of the array generated by Array.from()
.
Inside the body of the arrow function, it is calculated the value of each element of the returned array. This is done by adding the value of start
to index i
.
Finally, the createNumberRange
function returns the array of numbers generated using Array.from()
.