Fill an Array With a Single Value in JavaScript
Whether you're initializing a list of default values, setting placeholders, or simply repeating something like "apple"
across an entire array, JavaScript makes it remarkably easy to fill an array with a single repeated value. This can be useful when building UI grids, loading templates, mocking test data, or prepping for transformations.
In this tutorial, you'll learn several beginner-friendly techniques to fill an array with a single value using modern JavaScript methods. Let’s dive into the most practical approaches, all explained with simple examples.
Method 1: Using Array.fill()
The fill()
method is the most direct and widely-used way to fill an array with a single repeated value. It’s readable, elegant, and efficient for most use cases.
const filledArray = new Array(4).fill("apple");
console.log(filledArray);
["apple", "apple", "apple", "apple"]
Method 2: Using Array.from()
Array.from()
gives you more flexibility. Instead of just repeating the same value, you can use a mapping function to compute values. But for filling a single repeated value, it works just as well with a simple return.
const filledWithBanana = Array.from({ length: 5 }, () => "banana");
console.log(filledWithBanana);
["banana", "banana", "banana", "banana", "banana"]
Method 3: Using a for
Loop
If you're working in a context where modern methods aren’t available, or if you want full control over the filling process (perhaps with conditions), a classic for
loop is reliable and easy to understand.
const items = [];
for (let i = 0; i < 3; i++) {
items.push("cherry");
}
console.log(items);
["cherry", "cherry", "cherry"]
Method 4: Creating Multi-Dimensional Arrays
Sometimes, you may want not just a flat array, but an array of arrays—each filled with a repeated value. For this, combining Array.from()
with fill()
becomes very powerful.
const table = Array.from({ length: 3 }, () => new Array(2).fill("Item"));
console.log(table);
[["Item", "Item"], ["Item", "Item"], ["Item", "Item"]]
Choosing the Right Method
Use fill()
if you need a quick, one-liner solution and you're working with the same value. Use Array.from()
when you want more dynamic filling logic, like using indexes. Reach for for
loops when compatibility or control is important. And for more complex patterns like matrices or nested structures, mix and match techniques to get exactly what you need.
Final Thoughts
Filling an array with a single value isn’t just a small task—it’s a gateway to writing cleaner, more structured, and more intentional code. Whether you're building interfaces, transforming data, or simulating real-world scenarios, this technique helps you shape arrays in meaningful ways.
Once you've mastered these techniques, you'll see how often they appear in real-world JavaScript. So grab that virtual "apple," and start filling your arrays with confidence.
Comments
Loading comments...