Fill with Start and End Parameters
In this lesson, you'll learn how to use fill()'s optional start and end parameters to replace only specific portions of an array, giving you surgical precision over which elements get filled.
Targeting Specific Array Ranges
You've learned that fill() replaces array elements with a static value. By default, it fills the entire array. But you can use two additional parameters to control exactly which section gets filled:
array.fill(value, start, end)
start(optional): The index where filling begins (inclusive)end(optional): The index where filling stops (exclusive)
Think of it like highlighting text: you click where you want to start, then drag to where you want to stop—everything in between gets highlighted.
How It Works
const numbers = [1, 2, 3, 4, 5, 6];
// Fill from index 2 to index 5 (not including 5)
numbers.fill(0, 2, 5);
console.log(numbers); // [1, 2, 0, 0, 0, 6]
The elements at indices 2, 3, and 4 were replaced with 0. Index 5 was not filled (the end parameter is exclusive).
Omitting the End Parameter
If you omit end, filling continues to the end of the array:
const letters = ['a', 'b', 'c', 'd', 'e'];
letters.fill('x', 3); // Start at index 3, fill to the end
console.log(letters); // ['a', 'b', 'c', 'x', 'x']
Negative Indices Work Too
Negative values count backward from the end, just like with other array methods:
const items = [10, 20, 30, 40, 50];
items.fill(99, -3, -1); // Fill the 3rd-from-last to 1st-from-last (exclusive)
console.log(items); // [10, 20, 99, 99, 50]
Key Takeaway: Use fill(value, start, end) to replace only a specific range of array elements, with start inclusive and end exclusive—perfect for updating just the middle of an array.