Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
new Array(3).fill("x"); // ["x", "x", "x"]

Try it

JS Filling all or part

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS The shared-object trap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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) makes b and a the same array.
  • Objects are shared. Every slot receives the same reference. new Array(3).fill([]) gives three names for one array. Use Array.from({ length: 3 }, () => []) when each slot needs its own object.
  • Range rules: the range is start up to but not including end. Out-of-range indexes are clamped, and if start is not before end nothing changes.
  • It cannot grow an array. fill() only writes into indexes that already exist, so [].fill(0) stays empty. Create the length first with new Array(n) or Array.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 with map().
  • No computed values. fill() takes a value, not a function. To compute a value per slot, use Array.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.