Skip to content

JavaScript fill array with incrementing numbers/integer | Example code

  • by

Use a loop to fill an array of numbers 1…n in JavaScript. First, create an empty array with length then use a loop and store every value one by one in the Array.

JavaScript fill array with incrementing numbers

HTML Example code of JavaScript array containing 1 through to N where N is up to.

If don’t want to store anything in the array, use a container with the right length that you can iterate over.

Store value in Array

<script type="text/javascript">
        var foo = new Array(10); // create an empty array with length 10

        for(var i = 0; i < foo.length; i++){
           foo[i] =i+1;
       }
       console.log(foo);
   </script>

Output: Filling a array with 1 to 10 number by increasing it 1.

JavaScript fill array with incrementing numbers

Print value 1 to 10

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        var foo = new Array(10); // create an empty array with length 45

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

Output:

JavaScript fill array with incrementing numbers example html

Do comment if you have another example or doubts or suggestion on this 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 *