Range function in JavaScript
JavaScript doesn’t have a built-in equivalent of Python’s range function. Although a for loop isn’t difficult to write, I occasionally miss the convenience of range.
The popular lodash library includes a range function, but it’s also easy enough to implement yourself without any additional libraries.
The most compact way to generate the range [0..n) is:
[...Array(n).keys()]
Example:
for (const n of [...Array(3).keys()]) {
console.log(n);
}
/*
Output:
0
1
2
*/
This can also be written using Array.from(), which can be useful sometimes:
Array.from({ length: n }, (_, i) => i)
Example:
Array.from({ length: 3 }, (_, i) => {
console.log(i);
})
/*
Output:
0
1
2
*/
A more elaborate implementation may look like:
const range = (start, stop, step = 1) => {
if (start == null) {
throw 'range requires at least 1 parameter';
}
if (stop == null) {
[start, stop] = [0, start];
}
const size = Math.floor((stop - start) / step);
return Array.from({ length: size }, (_, i) => start + i * step);
}
Example:
console.log(range(6));
// Output: [ 0, 1, 2, 3, 4, 5 ]
console.log(range(4, 10));
// Output: [ 4, 5, 6, 7, 8, 9 ]
console.log(range(17, 28, 2));
// Output: [ 17, 19, 21, 23, 25 ]