The .fill() method is a useful tool for changing all elements in an array to a static value. It can be used to overwrite an entire array or just a specific portion of it.
Because it modifies the array it is called on, it is considered a mutative method.
1. Basic Syntax
array.fill(value, start, end)
- value: The value to fill the array with.
- start (Optional): The index to start filling (default is 0).
- end (Optional): The index to stop filling (default is array.length). The fill stops before this index.
2. Examples of Use
A. Filling an Entire Array
If you only provide the value, the entire array is overwritten.
const numbers = [1, 2, 3, 4];
numbers.fill(0);
console.log(numbers); // [0, 0, 0, 0]
B. Filling a Specific Range
You can target a specific section by providing start and end indices.
const fruits = ['apple', 'banana', 'cherry', 'date'];
fruits.fill('grape', 1, 3);
console.log(fruits); // ['apple', 'grape', 'grape', 'date']
C. Creating and Initializing Arrays
This is often used in combination with the Array constructor to create a pre-filled list.
const mask = new Array(5).fill(true);
console.log(mask); // [true, true, true, true, true]
3. The Object Reference Trap
This is the most important “gotcha” when using .fill(). If you fill an array with an object, every element in the array will point to the same reference in memory. Changing one will change them all.
// ❌ Potential Bug
const arr = new Array(3).fill({ name: "Guest" });
arr[0].name = "Alice";
console.log(arr[1].name); // "Alice" (Because both elements share the same object!)
Solution: If you need unique objects, use
Array.from()instead:Array.from({ length: 3 }, () => ({ name: "Guest" }))
