Skip to content

JavaScript array fill range | Example code

  • by

Use fill() method with map() function to fill JavaScript array in range. Or you can do declarative approach while using Array.from like this:

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

Array.from() and Array.keys() require an ES6 polyfill in order to work in all browsers.

JavaScript array fill range

Simple example code.

<!DOCTYPE html>

    function range(start, end) {
      return Array(end - start + 1).fill().map((_, idx) => start + idx)
    var result = range(0, 5);




JavaScript array fill range

ES6 create array with increasing number

//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want an array of numbers 1..n that you can later loop through.

var foo = new Array(45); // create an empty array with length 45

then when you want to use it… (un-optimized, just for example)

for(var i = 0; i < foo.length; i++){
  document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>'); 


Making use of the spread operator (...) and keys method, enables you to create a temporary array of size N to produce the indexes, and then a new array that can be assigned to your variable:

var foo = [ ...Array(N).keys() ];


You can first create the size of the array you need, fill it with undefined and then create a new array using map, which sets each element to the index.

var foo = Array(N).fill().map((v,i)=>i);


This should be initializing to length of size N and populating the array in one pass.

Array.from({ length: N }, (v, i) => i)


Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *