JavaScript Reference ยท Array
JavaScript Array fill() method
Reference for JavaScript Array fill(): overwrite a range of elements with one value in place, with start and end indexes, and the shared-object trap.
The fill() method overwrites elements of an array with a single static value, in place, and returns the same array. By default it fills everything; optional start and end arguments limit it to a range.
It is most often used to initialize a new array of a known size, as in new Array(5).fill(0). It mutates the array it is called on, so it does not create a copy.
new Array(3).fill("x"); // ["x", "x", "x"]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
fill(value) fill(value, start) fill(value, start, end)
| Name | Description |
|---|---|
value |
The value to store in every filled slot. The same value (or reference) is used each time. |
start |
Optional. Index at which to begin, default 0. Negative values count from the end; they are added to length. |
end |
Optional. Index at which to stop, exclusive, default length. Negative values count from the end. |
Return value: the modified array (the same object, not a copy).
Exceptions: a TypeError if the array is frozen, because fill() writes to it.
Usage notes
- It mutates. The original array changes and is also the return value, so
const b = a.fill(0)makesbandathe same array. - Objects are shared. Every slot receives the same reference.
new Array(3).fill([])gives three names for one array. UseArray.from({ length: 3 }, () => [])when each slot needs its own object. - Range rules: the range is
startup to but not includingend. Out-of-range indexes are clamped, and ifstartis not beforeendnothing changes. - It cannot grow an array.
fill()only writes into indexes that already exist, so[].fill(0)stays empty. Create the length first withnew Array(n)orArray.from({ length: n }). - Holes are filled. Empty slots of a sparse array become real elements, which is why
new Array(3).fill(undefined)can then be used withmap(). - No computed values.
fill()takes a value, not a function. To compute a value per slot, useArray.from({ length: n }, (_, i) => i * 2). - Typed arrays have their own
fill()with the same behavior.
Browser support
fill() is supported in every current browser.
Related
Array.from(),Array.prototype.copyWithin(),Array.prototype.splice()Array.prototype.with()for a non-mutating single-index replacement- Lessons: Arrays, Array recipes