fill()
ES6+Fills all the elements of an array from a start index to an end index with a static value.
Syntax
array.fill(value, start, end)Parameters
value any Value to fill the array with
start number optionalStart index (default: 0)
end number optionalEnd index (default: array.length)
Return Value
The modified array
Examples
const arr = [1, 2, 3, 4];
arr.fill(0, 1, 3);
console.log(arr); 📌 When to Use
Use fill() when you need to populate an array with a static value or initialize an array to a specific state. It's perfect for creating arrays of default values, resetting arrays, or creating placeholders.
⚠️ Common Mistakes
Using fill() with objects/arrays - all elements will reference the SAME object
Forgetting that fill() modifies the original array in place
Using new Array(n).fill({}) creates n references to the same object
✅ Best Practices
For arrays of unique objects, use Array.from({length: n}, () => ({}))
Use fill() with primitives (numbers, strings, booleans) to avoid reference issues
Combine with Array constructor: new Array(5).fill(0) creates [0,0,0,0,0]
⚡ Performance Notes
fill() is O(n) where n is the number of elements being filled. It's very efficient for initializing arrays. For creating arrays of unique objects, Array.from() with a map function is the correct approach, though slightly slower.
🌍 Real World Example
Creating a Grid or Matrix
Initialize a 2D grid for a game board or matrix calculations
// Create a 5-element array of zeros
const zeros = new Array(5).fill(0);
// [0, 0, 0, 0, 0]
// WRONG: Creates rows that share the same array!
const wrongGrid = new Array(3).fill(new Array(3).fill(0));
wrongGrid[0][0] = 1; // Changes ALL rows!
// CORRECT: Create unique row arrays
const grid = Array.from({length: 3}, () => new Array(3).fill(0));
grid[0][0] = 1; // Only changes first row
// [[1,0,0], [0,0,0], [0,0,0]]
// Reset portion of an array
const scores = [10, 20, 30, 40, 50];
scores.fill(0, 1, 4); // [10, 0, 0, 0, 50]