Skip to content

JavaScript generates a number sequence | Example code

  • by

You can generate a number sequence in JavaScript using fill and map method and store the values in Array.

JavaScript generate a number sequence Example

HTML example code generate array of sequential numbers in JavaScript.

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        function range(start, end) {
          return Array(end - start + 1).fill().map((_, idx) => start + idx)
      }
      var seqNumbers = range(9, 18); 
      console.log(seqNumbers);
  </script>
</body>
</html>

Output:

JavaScript generate a number sequence Example

Make re-usable function

This function will work to generate a sequence of numbers in javascript.

Let’s see an example to generate a number in the sequence (series) with step 3 up to 8 numbers.

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        function makeArray(count, content) {
           var result = [];
           if(typeof content == "function") {
              for(var i = 0; i < count; i++) {
                 result.push(content(i));
             }
         } else {
            for(var i = 0; i < count; i++) {
                result.push(content);
            }        
        }
        return result;
    }
        var myArray = makeArray(8, function(i) { return i * 3; });
        console.log(myArray)
</script>
</body>
</html>

Output

Make re-usable function generates a number sequence

Do comment if you have another example or doubts on this topic or codes.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading