Course contentsShow
← JavaScript
Lesson 844 of 2,72319. ArraysFree lesson

Creating Range Arrays with Array.from

Generate sequences of numbers by combining Array.from with length and a mapping function.

Creating Range Arrays with Array.from

You'll learn how to generate sequences of numbers (like 1, 2, 3, 4, 5) using Array.from with a length and mapping function.

The Core Idea

Sometimes you need an array filled with sequential numbers—a "range" of values. Instead of manually typing [0, 1, 2, 3, 4] or using a loop, you can combine Array.from with its mapping function to generate these sequences automatically. By creating an empty array with a specific length and then mapping over its indices, you can produce any numeric sequence you need.

How It Works

The pattern is straightforward: pass an object with a length property to Array.from, then use the mapping function's second parameter (the index) to generate your values:

// Create an array of numbers 0 through 4
const range = Array.from({ length: 5 }, (_, index) => index);
console.log(range); // [0, 1, 2, 3, 4]

// Create an array of numbers 1 through 5
const oneToFive = Array.from({ length: 5 }, (_, index) => index + 1);
console.log(oneToFive); // [1, 2, 3, 4, 5]

// Create even numbers from 0 to 8
const evens = Array.from({ length: 5 }, (_, index) => index * 2);
console.log(evens); // [0, 2, 4, 6, 8]

The first parameter in the mapping function is the element value (unused here, so we use _ as a convention), while the second is the index—which gives us our counting mechanism.

You can create any arithmetic sequence:

// Counting down from 10
const countdown = Array.from({ length: 5 }, (_, i) => 10 - i);
console.log(countdown); // [10, 9, 8, 7, 6]

Key Takeaway: Use Array.from({ length: n }, (_, index) => ...) to generate range arrays by transforming indices into your desired sequence—no loops required.