Course contentsShow
← JavaScript
Lesson 892 of 2,72320. Array Iteration and TransformationFree lesson

Creating Pre-Filled Arrays

Master techniques for initializing arrays with fill(), including combining with Array() or Array.from().

Creating Pre-Filled Arrays

You'll learn how to efficiently initialize arrays with predetermined values using fill() combined with Array() or Array.from().

The Core Idea

Sometimes you need an array that's already populated with values before you start working with it. Instead of manually adding elements one by one, JavaScript gives you powerful shortcuts to create pre-filled arrays in a single expression. This combines the array-creation techniques you've learned with the fill() method.

Combining Array() with fill()

The Array() constructor creates an array with a specific length, but those slots are empty. Chain fill() to populate them immediately:

// Create an array of 5 zeros
const zeros = Array(5).fill(0);
console.log(zeros); // [0, 0, 0, 0, 0]

// Create an array of 3 'hello' strings
const greetings = Array(3).fill('hello');
console.log(greetings); // ['hello', 'hello', 'hello']

// Create a 4-element array filled with objects
const boxes = Array(4).fill({ empty: true });
console.log(boxes); // [{empty: true}, {empty: true}, {empty: true}, {empty: true}]

Using Array.from() for Pre-Filling

Array.from() with a length object and mapping function offers more flexibility:

// Create an array of 5 ones using the mapping function
const ones = Array.from({ length: 5 }, () => 1);
console.log(ones); // [1, 1, 1, 1, 1]

// Create sequential values
const sequence = Array.from({ length: 5 }, (_, i) => i * 10);
console.log(sequence); // [0, 10, 20, 30, 40]

The Array.from() approach is especially useful when each element needs a unique value based on its position.

Key Takeaway: Use Array(length).fill(value) for simple repeated values, or Array.from({ length }, mapFn) when you need position-dependent initialization—both create ready-to-use arrays instantly.