To create an array containing the numbers from 1 to N in JavaScript, you can use one of the following methods:
1. Using Array.from()
(Recommended)
Most concise and efficient for modern browsers (ES6+):
const N = 5;
const arr = Array.from({ length: N }, (_, i) => i + 1);
// Output: [1, 2, 3, 4, 5]
How it works:
Array.from({ length: N })
creates an array ofN
empty slots.- The second argument is a mapping function that replaces each empty slot with
i + 1
, wherei
is the index (starting at 0).
2. Using Spread Operator and keys()
Leverages the spread operator and array indexing:
const N = 5;
const arr = [...Array(N).keys()].map(i => i + 1);
// Output: [1, 2, 3, 4, 5]
Breakdown:
Array(N)
creates an array ofN
empty slots..keys()
generates an iterator of indices[0, 1, ..., N-1]
.map(i => i + 1)
increments each index by 1.
3. Using a Loop
Explicitly push values into an array (works in all browsers):
const N = 5;
const arr = [];
for (let i = 1; i <= N; i++) {
arr.push(i);
}
// Output: [1, 2, 3, 4, 5]
4. Using fill()
and map()
Initialize an array with fill()
and map indices:
const N = 5;
const arr = Array(N).fill().map((_, i) => i + 1);
// Output: [1, 2, 3, 4, 5]
Note:
Array(N).fill()
fills the array withundefined
values..map((_, i) => i + 1)
replaces eachundefined
withi + 1
.
Edge Cases
- N = 0: Returns an empty array.
- Negative N: Returns an empty array.
Summary
- Best Practice: Use
Array.from({ length: N }, (_, i) => i + 1)
. - Legacy Browsers: Use the loop method.
- Avoid
new Array(N).map(...)
directly (due to sparse arrays).
Example Output for N = 3:
[1, 2, 3]