Array.prototype.fill
Fills an array with one value.
Available since: ES2015
Syntax
array.fill(value, start, end)Parameters
| Parameter | Type | Description |
|---|---|---|
| value | any | The value to fill the array with. |
| start | number | Optional. The position to start from. 0 by default. |
| end | number | Optional. The position to stop before. To the end by default. |
Return value
ArrayThe same array, filled with the value.
Examples
An array of five zeros:
console.log(new Array(5).fill(0).join(', '));Output:
0, 0, 0, 0, 0Filling part of an array:
console.log([1, 2, 3, 4].fill(9, 1, 3).join(', '));Output:
1, 9, 9, 4Notes
If you fill an array with an object or an array, every slot holds the same reference: new Array(3).fill([]) creates three references to one array. For independent values use Array.from({ length: 3 }, () => []).
See also
- Array.from — Creates an array from a string, Set, Map or another iterable.
- Array.prototype.length — The number of elements in an array.
Related recipes
In the tutorial
- Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.