Create an Array containing 1 to N numbers in JavaScript


Borislav Hadzhiev

Sat Oct 09 20212 min read

Create an Array containing 1 to N numbers #

To create an array containing numbers from 1 to N:

  1. Create an empty array that will hold the numbers.
  2. Use a for loop to iterate N times, starting at 1.
  3. For each iteration, push the loop's iteration index into the array.
const arr = []; const total = 5; for (let i = 1; i <= total; i++) { arr.push(i); } console.log(arr); // 👉️ [1, 2, 3, 4, 5]

In the for loop we iterate for N times, pushing the value of the i variable for the current iteration in the array.

If you want to start at a number different than 1, just change the value the i variable starts at.

An alternative and more modern approach is to use the Array.from method.

const total = 5; const arr = Array.from( {length: total}, (_, index) => index + 1 ); console.log(arr) // 👉️ [1, 2, 3, 4, 5]

The parameters we pass to the Array.from method are:

  1. how many elements the array should contain
  2. a function that gets called for each element in the array

The use an _ character to denote that we don't need the first parameter of the function, which is the value of the array element.

A call to Array.from(3) returns an array with 3 elements with the value of undefined.

However, we make use of the index of the array element. Indexes are zero-based in JavaScript, therefore we have to add 1 to get the desired result.

Note that the Array.from method is not supported by Internet Explorer versions 6-11. If you need to support the browser, use the for loop approach instead.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.