References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript array.fill() method

Method JavaScript All modern browsers Updated
Quick answer

The fill() method sets elements of an array to a fixed value, in place. [1, 2, 3].fill(0) becomes [0, 0, 0]. With start and end arguments it fills only a range. It's most often used with Array(n).fill(value) to create an array of n identical values.

Overview

fill() overwrites elements with a single value. Called with just a value, arr.fill(0) sets every element to 0. Add a start (and optional end) index to fill only part of the array: arr.fill(0, 2) fills from index 2 onward. It mutates the array in place and returns it.

By far its most common use is creating an initialized array. new Array(5).fill(0) gives [0, 0, 0, 0, 0] — five zeros — which is the standard idiom for a counter array, a grid row, or a placeholder list. Combined with map() you can then build sequences: Array(5).fill(0).map((_, i) => i) yields [0, 1, 2, 3, 4].

One sharp edge: if you fill with an object or array, every slot gets the same reference, not a copy. Array(3).fill([]) creates three slots all pointing at one array, so pushing to one appears to change "all three". When you need distinct objects per slot, use Array.from({length: n}, () => ({})) instead.

Syntax

array.fill(value)
array.fill(value, start)
array.fill(value, start, end)

new Array(5).fill(0)   // [0, 0, 0, 0, 0]
[1, 2, 3, 4].fill(9, 1, 3)  // [1, 9, 9, 4]

Parameters

The array.fill() method accepts the following parameters.

Parameter Description
value The value to write into the array.
start Optional. Index to start filling from. Defaults to 0.
end Optional. Index to stop before (not included). Defaults to the array length.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const zeros = new Array(5).fill(0);
  const range = Array(5).fill(0).map((_, i) => i + 1);

  document.getElementById('out').textContent =
    'zeros: ' + zeros.join(', ') + '\n' +
    'range: ' + range.join(', '); // zeros: 0,0,0,0,0 / range: 1,2,3,4,5
</script>

Best practices

  • Create an initialized array with new Array(n).fill(value).
  • Build sequences by chaining: Array(n).fill(0).map((_, i) => i).
  • Never fill with a shared object/array if slots must be independent — use Array.from({length: n}, () => ({})).
  • Pass start/end to fill only a range of the array.

Frequently asked questions

How do I create an array of n zeros?
Use new Array(n).fill(0), which creates an array of length n filled with zeros.
Why do all elements change when I fill with an object?
Because fill() puts the same reference in every slot. Use Array.from({length: n}, () => ({})) to get independent objects.
Does fill() change the original array?
Yes, it fills in place and returns the same array.
How do I fill only part of an array?
Pass start and end indices: arr.fill(value, start, end) fills the range, end excluded.