Creating number ranges

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 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]

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.