Question
I want to create a JavaScript array containing the numbers 1 through N, where N is only known at runtime.
One approach is to use a loop like this:
var foo = [];
for (var i = 1; i <= N; i++) {
foo.push(i);
}
Are there alternative ways to build this array, especially using a more declarative style instead of manually pushing values in a loop?
Short Answer
By the end of this page, you will understand how to generate a sequence like 1...N in JavaScript, why loops are still valid, and how built-in tools such as Array.from() can make this pattern shorter and clearer.
Concept
In JavaScript, creating an array of numbers from 1 to N is really about generating a numeric range.
A range is a sequence of values that follow a pattern:
1, 2, 3, 4, 50, 1, 2, 3, 410, 20, 30
JavaScript does not have a built-in range literal like some other languages. That means you usually create ranges using:
- a
forloop Array.from()- array keys and mapping
- a reusable helper function
Your original loop is completely valid. In fact, it is often the clearest solution for beginners. But modern JavaScript provides more expressive options when you want to describe the result rather than manually build it step by step.
This matters in real programming because generating ranges is common when:
- paginating results
- building dropdowns such as years or days
- creating test data
- repeating operations a fixed number of times
- indexing rows, columns, or steps
So the real concept is not just “avoiding a loop.” It is learning how JavaScript constructs arrays from patterns.
Mental Model
Think of this like filling numbered tickets into a box.
- A
forloop means: “Start at ticket1, keep adding the next ticket until you reachN.” Array.from()means: “Give me a box withNslots, and for each slot, compute the value that should go there.”
Both approaches still do repeated work internally. The difference is mostly how you express your intent:
- loop: how to build it
- declarative method: what array you want
So even when you “avoid the loop,” JavaScript is still iterating somewhere under the hood.
Syntax and Examples
A modern and common way to create an array from 1 to N is with Array.from().
const N = 5;
const numbers = Array.from({ length: N }, (_, index) => index + 1);
console.log(numbers); // [1, 2, 3, 4, 5]
How this works
{ length: N }creates an array-like object withNslots.Array.from()turns it into a real array.- The callback runs once for each position.
indexstarts at0, so we add1to get1...N.
Traditional loop version
const numbers = [];
for (let i = ; i <= N; i++) {
numbers.(i);
}
Step by Step Execution
Consider this code:
const N = 4;
const result = Array.from({ length: N }, (_, index) => index + 1);
console.log(result);
Step by step
Nis set to4.{ length: N }becomes{ length: 4 }.Array.from()prepares to create an array with 4 items.- The callback runs once for each index:
- index
0→0 + 1→1 - index
1→1 + 1→2 - index
2→2 + 1→3
- index
Real World Use Cases
Generating arrays from 1 to N appears in many practical situations.
Pagination
const totalPages = 5;
const pages = Array.from({ length: totalPages }, (_, i) => i + 1);
// [1, 2, 3, 4, 5]
Use this to render page buttons in a UI.
Year dropdowns
const numberOfYears = 10;
const years = Array.from({ length: numberOfYears }, (_, i) => 2020 + i);
Useful for forms and filters.
Generating placeholder rows
const skeletonRows = Array.from({ length: 3 }, (_, i) => ({ id: i + , : }));
Real Codebase Usage
In real projects, developers often wrap range generation inside helper functions so the intent is clear.
Common helper pattern
function range(start, end) {
return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}
console.log(range(1, 5)); // [1, 2, 3, 4, 5]
This is more reusable than hardcoding 1...N every time.
Guard clause for invalid input
function rangeOneToN(n) {
if (!Number.isInteger(n) || n < 1) {
return [];
}
return Array.from({ length: n }, (_, i) => i + 1);
}
This avoids bugs when n is negative, not a number, or not an integer.
Common Mistakes
Here are common mistakes beginners make when creating a range.
Off-by-one errors
Broken code:
const numbers = Array.from({ length: 5 }, (_, i) => i);
console.log(numbers); // [0, 1, 2, 3, 4]
If you want 1...N, add 1:
const numbers = Array.from({ length: 5 }, (_, i) => i + 1);
Using new Array(N).map(...)
Broken code:
const numbers = new Array(5).map((_, i) => i + 1);
console.(numbers);
Comparisons
Here is a comparison of common ways to create a range in JavaScript.
| Approach | Example | Best for | Notes |
|---|---|---|---|
for loop | for (let i = 1; i <= n; i++) | Beginners, explicit logic | Very clear and efficient |
Array.from() | Array.from({ length: n }, (_, i) => i + 1) | Clean modern code | Very common and readable |
new Array(n).fill().map() | new Array(n).fill(0).map((_, i) => i + 1) | When you want to use map() | Works, but more verbose |
| Helper function | range(1, n) |
Cheat Sheet
Create 1...N
const arr = Array.from({ length: N }, (_, i) => i + 1);
Create 0...(N-1)
const arr = Array.from({ length: N }, (_, i) => i);
Loop version
const arr = [];
for (let i = 1; i <= N; i++) {
arr.push(i);
}
Reusable helper
function rangeOneToN(n) {
if (!Number.isInteger(n) || n < 1) return [];
return Array.from({ : n }, i + );
}
FAQ
Is a for loop bad for creating an array from 1 to N?
No. A for loop is a clear and efficient solution. Modern alternatives are mainly about readability and style.
What is the shortest modern JavaScript way to create 1...N?
Array.from({ length: N }, (_, i) => i + 1)
Why does new Array(N).map(...) not work properly?
Because new Array(N) creates empty slots, and map() skips them. Use Array.from() or .fill() first.
Can I create a reusable range function in JavaScript?
Yes:
function range(start, end) {
return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}
Mini Project
Description
Build a small utility that generates page numbers for a pagination component. This demonstrates how to create an array from 1 to N in a practical way, while also validating input so the function behaves safely.
Goal
Create a function that returns an array of page numbers from 1 to a given total page count.
Requirements
- Write a function named
createPageNumbers. - Return an empty array if the input is not a positive integer.
- Return page numbers starting at
1and ending atN. - Test the function with valid and invalid inputs.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.