Search code examples
javascriptarraysecmascript-6

How to generate range of numbers from 0 to n in ES2015 only?


I have always found the range function missing from JavaScript as it is available in python and others? Is there any concise way to generate range of numbers in ES2015 ?

EDIT: MY question is different from the mentioned duplicate as it is specific to ES2015 and not ECMASCRIPT-5. Also I need the range to be starting from 0 and not specific starting number (though it would be good if that is there)


Solution

  • You can use the spread operator on the keys of a freshly created array.

    [...Array(n).keys()]

    or

    Array.from(Array(n).keys())

    The Array.from() syntax is necessary if working with TypeScript