Generating [1, 2, ..., N] in JavaScript is cleanest with Array.from({ length: n }, (_, i) => i + 1). A plain new Array(n) alone creates sparse “empty” slots that .map() skips, whereas Array.from() with an array-like { length: n } object visits every index from 0 to n - 1 reliably.
1. Using Array.from() (Recommended)
Pass { length: n } as the first argument to Array.from() and map each zero-based index i to i + 1:
function range1ToN(n) {
if (!Number.isInteger(n) || n < 0) {
throw new RangeError("n must be a non-negative integer");
}
return Array.from({ length: n }, (_, i) => i + 1);
}
console.log(range1ToN(5)); // [1, 2, 3, 4, 5]
console.log(range1ToN(0)); // []
2. Generalizing to Custom Start, End, and Step
When you need more than 1 through N—such as 0 to N - 1, a custom starting number, or stepping by 2—a small helper keeps intent obvious:
function range({ start = 1, end, step = 1 }) {
if (step === 0) {
throw new RangeError("step must not be zero");
}
const result = [];
if (step > 0) {
for (let current = start; current <= end; current += step) {
result.push(current);
}
} else {
for (let current = start; current >= end; current += step) {
result.push(current);
}
}
return result;
}
console.log(range({ end: 5 })); // [1, 2, 3, 4, 5]
console.log(range({ start: 0, end: 4 })); // [0, 1, 2, 3, 4]
console.log(range({ start: 2, end: 10, step: 2 })); // [2, 4, 6, 8, 10]
3. Common Traps to Avoid
- Chaining
.map()directly onnew Array(n):new Array(5).map((_, i) => i + 1)returnsbecause.map()skips empty holes in sparse arrays. - Forgetting
n = 0or negative/non-integer inputs: Guard against negative or non-integer lengths so callers get a clear error or an empty array instead of unexpected behavior. - Using huge
Nin memory-sensitive code: Materializing an array of millions of numbers allocates significant heap memory—if you only iterate once, a generator function (function*) avoids allocating the full array up front.
TL;DR: Use Array.from({ length: n }, (_, i) => i + 1) to generate [1, 2, ..., n], avoid new Array(n).map(...) due to sparse slots, and use a for loop or generator when you need custom steps or large ranges.
Are you generating a small index array for UI/pagination, a custom step/start range, or iterating over a very large N?
