Mastering Array Manipulation: A Guide to array.fill
What is array.fill?
- It's used to fill all the elements of an array with a static value, starting from a specified index (optional) to an optional end index.
- It's a method built into JavaScript's
Array
object.
Syntax
array.fill(value, start, end);
Parameters
end
(optional): The index at which to stop filling (exclusive). Defaults to the entire array length.start
(optional): The index at which to begin filling. Defaults to 0 (the first element).value
(required): The value to fill the array elements with. This can be any primitive data type (number, string, boolean, etc.) or an object.
Return Value
- The
fill
method modifies the original array and returns the modified array itself.
Example
const numbers = [1, 2, 3, 4, 5];
const filledArray = numbers.fill(0, 2); // Fill elements from index 2 (inclusive) to the end with 0
console.log(filledArray); // Output: [1, 2, 0, 0, 0]
Important Points
- If an object is used as the
value
, all elements refer to the same object in memory (shallow copy). For deep copies, consider using spread syntax (...
) or libraries likelodash
. - If
end
is less thanstart
, no elements are filled. - If
end
is greater than the array length, it's set to the array length. - If
start
is negative, it's treated as zero (the first element).
Use Cases
- Resetting parts of an array to a specific value.
- Initializing arrays with placeholders before filling them with actual data.
- Creating arrays with predefined values (e.g., an array of zeros for calculations).
const zeros = new Array(10).fill(0); // Create an array of 10 zeros
console.log(zeros); // Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Filling a specific range with a value
const colors = ["red", "green", "blue", "purple", "yellow"];
// Fill elements from index 2 (inclusive) to index 4 (exclusive) with "black"
const updatedColors = colors.fill("black", 2, 4);
console.log(updatedColors); // Output: ["red", "green", "black", "black", "yellow"]
Filling the entire array with a value (omitting start and end)
const scores = [75, 82, 90, -1, 68];
// Fill all elements with -1 (assuming scores might need initialization)
scores.fill(-1);
console.log(scores); // Output: [-1, -1, -1, -1, -1]
Using a negative start index (treated as zero)
const letters = ["a", "b", "c", "d", "e"];
// Fill elements from index -1 (treated as 0) to index 2 (exclusive) with "X"
const modifiedLetters = letters.fill("X", -1, 2);
console.log(modifiedLetters); // Output: ["X", "X", "c", "d", "e"]
Using an end index greater than the array length (set to array length)
const fruits = ["apple", "banana", "orange"];
// Fill elements from index 1 to index 5 (set to array length, 3) with "mango"
const updatedFruits = fruits.fill("mango", 1, 5);
console.log(updatedFruits); // Output: ["apple", "mango", "mango"]
const people = [];
// Create an object with name and age properties
const personTemplate = { name: "", age: 0 };
// Fill the people array with the same personTemplate object (shallow copy)
people.fill(personTemplate, 0, 2); // Assuming you want 2 "people"
console.log(people); // Output: [{ name: "", age: 0 }, { name: "", age: 0 }]
// Modifying one person affects all since it's the same object reference
people[0].name = "Alice";
console.log(people); // Output: [{ name: "Alice", age: 0 }, { name: "Alice", age: 0 }]
for loop
- Can be less concise than
array.fill
for simple cases. - Offers more control over the filling logic (e.g., conditional filling).
- Suitable for older browsers that don't support
array.fill
.
const numbers = new Array(5);
// Fill all elements with 0 using a for loop
for (let i = 0; i < numbers.length; i++) {
numbers[i] = 0;
}
console.log(numbers); // Output: [0, 0, 0, 0, 0]
Array.from() + map()
- Can be less performant than
array.fill
for simple cases. - Can be used for more complex filling logic (e.g., generating a sequence of numbers).
- Creates a new array with the desired length and applies a mapping function to each element.
// Create an array of 5 elements filled with the index value using Array.from() + map()
const indexedArray = Array.from({ length: 5 }, (_, i) => i);
console.log(indexedArray); // Output: [0, 1, 2, 3, 4]
Spread syntax (with or without map())
- Not suitable for modifying an existing array.
- Can be slightly less readable than
array.fill
for specific value filling. - Concise syntax for creating an array with a repeated element.
// Create an array of 3 elements filled with "X" using spread syntax
const xArray = [...new Array(3)].map(() => "X");
console.log(xArray); // Output: ["X", "X", "X"]
Array constructor + fill()
- More verbose than
array.fill
and typically unnecessary for existing arrays. - Similar to
array.fill
but creates a new array with the desired length first.
// Create an array of 4 elements filled with 10 using Array constructor + fill()
const tensArray = new Array(4).fill(10);
console.log(tensArray); // Output: [10, 10, 10, 10]
- If you specifically need to modify an existing array,
array.fill
is the most efficient and concise option. - For simple filling of new arrays with the same value, consider spread syntax.
- If you need more control over the filling logic, use
Array.from
+map
. - If browser compatibility is a concern and you need basic filling, use a
for
loop.