JavaScript(JS) array method - fill

http‮i.www//:s‬giftidea.com

The fill() method is an array method in JavaScript that fills all the elements of an array with a static value. This method modifies the original array and returns a reference to the modified array.

Here's the syntax of the fill() method:

array.fill(value, start, end);
  • array is the array that the fill() method is called on.
  • value is the value that should be used to fill the array.
  • start is an optional argument that specifies the index at which to start filling the array. If start is not specified, the fill() method starts filling the array from index 0.
  • end is an optional argument that specifies the index at which to stop filling the array. If end is not specified, the fill() method fills the array up to the end.

The fill() method fills all the elements of the array with the specified value. If start and end are specified, the fill() method only fills the elements between the specified indices.

Here's an example of how to use the fill() method:

let array = [1, 2, 3, 4, 5];

array.fill(0, 2, 4);

console.log(array); // [1, 2, 0, 0, 5]

In this example, we have an array array containing the elements [1, 2, 3, 4, 5]. We use the fill() method to fill the elements between indices 2 and 4 with the value 0. The fill() method modifies the original array, so array now contains the elements [1, 2, 0, 0, 5]. The console.log() statement outputs the value of array, which is [1, 2, 0, 0, 5].

Note that the fill() method was introduced in ECMAScript 6, so it may not be supported by older browsers.