Published: October 02 2021

Vanilla JS - Create an array with a range of numbers in a JavaScript

This tutorial includes some quick examples of how to generate a range of numbers (e.g. [0, 1, 2, ..., N]) in an array in JavaScript.

The below examples include creating an array with ten numbers from zero to nine ([0, 1, 2, ..., 9]), an array with the range one to ten ([1, 2, 3, ..., 10]), an array with the range five to twenty ([5, 6, 7, ..., 20]), and an array with the range zero to one hundred with a step size of ten ([0, 10, 20, ..., 100]).

Here they are in action: (See on StackBlitz at https://stackblitz.com/edit/vanilla-js-create-array-with-range-of-numbers)


JavaScript Create Range Example Code

The code snippets use the following Vanilla JS tools to create a range of numbers in an array:

  • the Array() function creates a new javascript array with a specified number of empty slots (e.g. Array(10) creates the array [empty x 10]).
  • the Array.keys() method returns a new iterator object with the key/index of each slot in an array (e.g. 0, 1, 2, ..., N).
  • the ES6 Spread Operator (...) expands/converts the keys iterator object into a list of elements that can be passed to a literal Array constructor ([elem1, elem2, ..., elemN]).
  • the Array.map() function is used to create a new array with a modified range of numbers.
  • the Math.floor() function rounds a number down to the nearest integer, it's used in the last example to ensure a whole number is passed to the Array() function regardless of the step size.
(function() {
    // 0 to 9
    const range = [...Array(10).keys()];
    document.getElementById('rangeOne').innerHTML = JSON.stringify(range);
})();

(function() {
    // 1 to 10
    const start = 1;
    const end = 10;
    const range = [...Array(end - start + 1).keys()].map(x => x + start);
    document.getElementById('rangeTwo').innerHTML = JSON.stringify(range);
})();

(function() {
    // 5 to 20
    const start = 5;
    const end = 20;
    const range = [...Array(end - start + 1).keys()].map(x => x + start);
    document.getElementById('rangeThree').innerHTML = JSON.stringify(range);
})();

(function() {
    // 0 to 100 step 10
    const start = 0;
    const end = 100;
    const step = 10;
    const arrayLength = Math.floor(((end - start) / step)) + 1;
    const range = [...Array(arrayLength).keys()].map(x => (x * step) + start);
    document.getElementById('rangeFour').innerHTML = JSON.stringify(range);
})();


More info on JavaScript functions used

For more info on the Vanilla JS functions and operator used in the example see the below links:

 


Need Some Vanilla JS Help?

Search fiverr for freelance Vanilla JS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by