Follow The New Tutorial updates on WhatsApp, Telegram or YouTube.

JavaScript Array fill() method

The JavaScript array fill() method fills the elements of the given array with the specified static values.

The fill() method overwrites the original array.

JavaScript Array fill() method modifies the original array.

JavaScript Array fill() method returns undefined, if no element satisfies the condition.

Syntax

array.fill(value, start, end)

Parameters: This method accepts three parameters as mentioned above and described below: 

  • value – The static value to be filled.
  • start – It is optional. It represents the index from where the value starts filling.
    • By default, it is 0.
  • end – It is optional. It represents the index where the value stops filling.
    • By default, it is length-1.

If start or end is negative, indexes are counted from backwards.

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

Return Value

The modified array.

Examples

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
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 ]