## DEV Community

Dom Habersack

Posted on • Originally published at islovely.co

# 🔥 Create number ranges in JavaScript

To get a range of numbers in JavaScript, initialize an array by spreading the keys of another array into it. You can shift the range up or down, or do things like have it contain only even numbers.

``````const range = [...Array(5).keys()] // ⇒ [0, 1, 2, 3, 4]

// the number in `Array(number)` describes how many values you want
[...Array(7).keys()] // ⇒ [0, 1, 2, 3, 4, 5, 6]

// you can `map` the values to shift or otherwise manipulate the range
[...Array(4).keys()].map(n => n + 3) // ⇒ [3, 4, 5, 6]
[...Array(4).keys()].map(n => n - 3) // ⇒ [-3, -2, -1, 0]
[...Array(4).keys()].map(n => n * 2) // ⇒ [0, 2, 4, 6]
`````` Dom Habersack

I find the shorter version easier to read, but I’d go with your line if performance was more important. 👍 Thanks for sharing it! JoelBonetR 🥇 • Edited

Easier way:

``````const getRange = (e) =>
Array.from({length:e},(v, i)=> i+1);

getRange(4); // [ 1, 2, 3, 4 ]
``````

But one nice to have in ranges is to be able to define both the initial and the end values, hence:

``````const getRangeBetween = (ini, end) =>
Array.from({length:end},(v, i)=> i+1).filter( x => x > ini && x < end);

getRangeBetween(2, 9) // [ 3, 4, 5, 6, 7, 8 ]
``````

You can also made it inclusive by doing

``````const getRangeBetween = (ini, end) =>
Array.from({length:end},(v, i)=> i+1).filter( x => x >= ini && x <= end);

getRangeBetween(2, 9) // [ 2, 3, 4, 5, 6, 7, 8, 9 ]
``````

Only "bad thing" is that this method doesn't work for negative numbers neither for getting a float range (at least this alone).

You can use map for that instead of filter, though 😁

Cheers! Dom Habersack

Nice yes, putting this in a helper function is definitely the way to go.