DEV Community

Dom Habersack
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]
Enter fullscreen mode Exit fullscreen mode

Discussion (5)

Collapse
alfredosalzillo profile image
Alfredo Salzillo šŸŗ • Edited on

Why not

Array(5).fill(0).map((_, i) => I)
Enter fullscreen mode Exit fullscreen mode

Instead of keys and destructuring

Collapse
domhabersack profile image
Dom Habersack Author

I find the shorter version easier to read, but Iā€™d go with your line if performance was more important. šŸ‘ Thanks for sharing it!

Collapse
joshuakb2 profile image
Joshua Baker

I always copy and paste one of these:

function range(n) {
    let r = [];
    for (let i = 0; i < n; i++) r.push(i);
    return r;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
domhabersack profile image
Dom Habersack Author

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

Collapse
hardikchopra242 profile image
Hardik Chopra

Very effective shortcut šŸ”„