How to Create an Array Containing 1…N in JavaScript

To create an array containing the numbers from 1 to N in JavaScript, you can use a “for loop” to iterate through the range of numbers and add each number to the array.

Example

function createArray(N) {
  const arr = [];

  for (let i = 1; i <= N; i++) {
    arr.push(i);
  }

  return arr;
}

const N = 5;
const arrayWithNumbers = createArray(N);

console.log(arrayWithNumbers);

Output

[ 1, 2, 3, 4, 5 ]

In the above code, we defined a function createArray(N) that takes a number N as its argument.

Inside the function, we created an empty array arr and use a for loop to iterate through the numbers from 1 to N.

We added each number to the array using the push() method.

Finally, the function returns the populated array.

Leave a Comment