how to create an array of size n with numbers filled from 1 to n in javascript

index.tsx
// Initializing variables
let n = 10; // size of the array
let arr = []; // declaring an empty array

// Filling the array using loop
for(let i=1; i<=n; i++){
   arr.push(i);
}

console.log(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
231 chars
11 lines

In the above code block, we have initialized two variables n and arr. n specifies the size of the array and arr is an empty array which we need to fill with numbers.

Then we have used a for loop to iterate from 1 to n and at each iteration, we have pushed the current loop counter value to the arr using push() method.

Finally, we have printed the resultant array using console.log() method.

gistlibby LogSnag