Array.prototype.fill()
fill(value[, start[, end]]) Returns:
array · Updated March 13, 2026 · Array Methods array fill mutation
The fill() method changes all elements in an array to a static value from a start index to an end index. It mutates the original array and returns the modified array.
Syntax
fill(value)
fill(value, start)
fill(value, start, end)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
value | any | — | The value to fill the array with |
start | number | 0 | Start index (inclusive). Negative counts from the end. |
end | number | array.length | End index (exclusive). Negative counts from the end. |
Examples
Basic usage
const arr = [1, 2, 3, 4, 5];
arr.fill(0);
console.log(arr);
// [0, 0, 0, 0, 0]
// Fill with a specific value
const nums = [1, 2, 3, 4, 5];
nums.fill(9, 1, 3);
console.log(nums);
// [1, 9, 9, 4, 5]
Using negative indices
const arr = [1, 2, 3, 4, 5];
// Start at second-to-last, fill to end
arr.fill(0, -2);
console.log(arr);
// [1, 2, 3, 0, 0]
// Fill middle portion
arr.fill('x', 1, -1);
console.log(arr);
// [1, 'x', 'x', 'x', 0]
Creating initialized arrays
// Create an array of zeros
const zeros = new Array(5).fill(0);
console.log(zeros);
// [0, 0, 0, 0, 0]
// Create a 2D matrix
const matrix = Array(3).fill(null).map(() => Array(3).fill(0));
console.log(matrix);
// [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Common Patterns
Initializing a buffer:
const buffer = new ArrayBuffer(16);
const bytes = new Uint8Array(buffer).fill(0xFF);
Resetting an array:
let scores = [10, 20, 30, 40, 50];
scores.fill(0);
console.log(scores);
// [0, 0, 0, 0, 0]
See Also
- array::map — transform array elements
- array::copyWithin — copy array segments
- array::from — create arrays from iterables