Creating and array of a range of numbers in JavaScript

Published

In languages like Ruby, there are often convenience methods to generate an array of numbers to iterate over, often called a range. For example:

(0..5).map { |x| puts x }

JavaScript doesn’t have such a method but using more recent version of ES6 you can get close to that behavior:

Array.from(Array(5).keys()); //=> [ 0, 1, 2, 3, 4 ]

Or and even cleaner version using array destructuring:

[...Array(5).keys()]; //=> [ 0, 1, 2, 3, 4 ]

Of course you could also use a library for this instead. Here is lodash’s _.range:

_.range(5); //=> [ 0, 1, 2, 3, 4 ]