JavaScript (ES2026) reference · Array Methods
JavaScript Array fill() Method
Fill all or part of an array with a static value, changing it in place. Often used to create an array of defaults.
JavaScript (ES2026) Since ES2015
Syntax
array.fill(value, start, end)
Parameters
| Parameter | Description |
|---|---|
value |
The value to fill with. |
start, end optional |
Only fill this range. |
Return value
The modified array.
Examples
console.log(new Array(3).fill(0));
console.log([1, 2, 3, 4].fill(9, 1, 3));
Output
[ 0, 0, 0 ] [ 1, 9, 9, 4 ]
const bad = new Array(2).fill([]);
bad[0].push("x");
console.log(bad); // the same array twice!
const good = Array.from({ length: 2 }, () => []);
good[0].push("x");
console.log(good);
Output
[ [ 'x' ], [ 'x' ] ] [ [ 'x' ], [] ]
Version history
| Version | Change |
|---|---|
| JavaScript ES2015 | Added |
Related
Array.from()· Create a new array from an iterable or array-like object, with an optional function to map each element.array.copyWithin()· Copy a slice of the array to another position in the same array, overwriting what's there. Changes the array in place.- JavaScript Arrays · tutorial
- JavaScript Array Methods · tutorial