How to create an array of numbers from 1 to N
Short answer
Array.from() with a length creates an array and fills it using the index:
const numbers = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(numbers.join(', '));Output:
1, 2, 3, 4, 5With a step
A function for a range from start to end with any step:
const range = (start, end, step = 1) =>
Array.from({ length: Math.floor((end - start) / step) + 1 }, (_, i) => start + i * step);
console.log(range(0, 20, 5).join(', '));
console.log(range(10, 15).join(', '));Output:
0, 5, 10, 15, 20
10, 11, 12, 13, 14, 15The same value
fill() fills an array with one value:
console.log(new Array(3).fill(0).join(', '));Output:
0, 0, 0Common mistake
fill() with an object puts the same object into every cell. Use Array.from() with a function to get separate objects:
const shared = new Array(2).fill({ count: 0 });
shared[0].count = 5;
const separate = Array.from({ length: 2 }, () => ({ count: 0 }));
separate[0].count = 5;
console.log(shared[1].count, separate[1].count);Output:
5 0Functions used in this recipe
- Array.from — Creates an array from a string, Set, Map or another iterable.
- Array.prototype.fill — Fills an array with one value.
- Array.prototype.keys — Returns the indexes of an array.