Javascript Range Function

29 October 2021

Updated: 03 September 2023

Something i often find myself needing is a way to create a range in javascript, similar to what python has

Here’s a basic implementation of something that works like that:

1
const range = (start, end, count, includeEnd = false) => {
2
const space = (end - start) / (count - includeEnd)
3
return new Array(count).fill(0).map((_, i) => start + i * space)
4
}

The above will output something like:

1
const withoutEnd = range(20, 21, 5)
2
// withoutEnd === [ 20, 20.2, 20.4, 20.6, 20.8 ]
3
4
const withEnd = range(20, 21, 5, true)
5
// withEnd === [ 20, 20.25, 20.5, 20.75, 21 ]