Array.prototype.fill()
Mostly used to make new Array(n) usable. Its one serious trap is that an object or array argument is stored once and shared by every slot.
Demo
Every slot in the range is overwritten with the same value, and the array is modified in place. With numbers that is all there is to it. The behaviour worth knowing sits outside what a number input can show: fill evaluates its argument ONCE, so filling with an object or array puts the very same reference in every slot — mutating one visibly mutates them all.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| value | any | yes | The value written to every slot in the range. Evaluated ONCE — objects and arrays are shared, not copied. |
| start | number | no (0) | Index to start filling at. Negative counts from the end. |
| end | number | no (length) | Index to stop BEFORE. Negative counts from the end. |
Return value
Array — The SAME array, with the range overwritten. Mutates in place — the return value is a reference to the original.
Common patterns
const zeros = new Array(5).fill(0);
const grid = Array.from({length: 3}, () => new Array(3).fill(0));
buffer.fill(0);
Examples
Pitfalls
const a = new Array(2).fill([]); a[0].push(1); a
const a = Array.from({length: 2}, () => []); a[0].push(1); a
const a = [1, 2]; const b = a.fill(0); a
const b = [...a].fill(0);
[1, 2, 3].fill(0, 1, 2)
[1, 2, 3].fill(0, 1, 3)
When to use
- Turning new Array(n) into a dense, usable array
- Resetting an existing array in place
- Initialising a numeric buffer to a default
- The value is an object or array → Array.from with a factory
- The array is shared or state → copy first
- Each slot needs a different value → Array.from with an index callback
Notes
FAQ
Because fill stores one reference in every slot. new Array(3).fill([]) creates a single array and points all three slots at it. Use Array.from with a factory function, which runs once per slot.
Array.from({length: 3}, () => []);