Search code examples
javascriptarraysnumbers

Efficient way to create and fill an array with consecutive numbers in range


for the moment i use this JavaScript to create an array with n numbers from 0 to n

// javascript populate array 
var n=1000;
var arr=[n];
for (i=n;i>=0;i--) {
arr[i]=i;
console.log(arr[i]);
} 

is it the fast/right way to do the task?


Solution

  • You can do declarative approach while using Array.from like this:

    arr = Array.from({length: 20}, (e, i)=> i)
    console.log(arr)