JavaScript Array fill()

The JavaScript Array fill() method returns an array by filling all elements with a static value.

The syntax of the fill() method is:

arr.fill(value, start, end)

Here, arr is an array.


fill() Parameters

The fill() method takes in:

  • value - Value to fill the array with.
  • start (optional) - Start index (default is 0).
  • end (optional) - End index (default is Array.length) (exclusive).

Return value from fill()

  • Returns the modified array, filled with value from start to end.

Notes:

  • If start or end is negative, indexes are counted from backwards.
  • Since fill() is a mutator method, it changes the array itself (not a copy) and returns it.

Example: Filling array with fill() method

var prices = [651, 41, 4, 3, 6];

// if only one argument, fills all elements
new_prices = prices.fill(5);
console.log(prices); // [ 5, 5, 5, 5, 5 ]
console.log(new_prices); // [ 5, 5, 5, 5, 5 ]

// start and end arguments specify what range to fill
prices.fill(10, 1, 3);
console.log(prices); // [ 5, 10, 10, 5, 5 ]

// -ve start and end to count from back
prices.fill(15, -2);
console.log(prices); // [ 5, 10, 10, 15, 15 ]

// invalid indexed result in no change
prices.fill(15, 7, 8);
console.log(prices); // [ 5, 10, 10, 15, 15 ]

prices.fill(15, NaN, NaN);
console.log(prices); // [ 5, 10, 10, 15, 15 ]

Output

[ 5, 5, 5, 5, 5 ]
[ 5, 5, 5, 5, 5 ]
[ 5, 10, 10, 5, 5 ]
[ 5, 10, 10, 15, 15 ]
[ 5, 10, 10, 15, 15 ]
[ 5, 10, 10, 15, 15 ]

Here, we can see that the fill() method fills the array from start to end with the passed value. The fill() method changes the array in place as well as returns the modified array.

The start and end parameters are optional and can also be negative (to count backwards).

The array is not updated if the start and end arguments are invalid.


Recommended Reading: JavaScript Array