JavaScript fill()
The fill()
method in JavaScript is used to fill all elements of an array from a start index to an end index with a static value. This method modifies the original array and returns the modified array.
Syntax
The syntax of the fill()
method is as follows:
array.fill(value, start, end)
value
: The value to fill the array with.start
(optional): The index at which to start filling the array. Default is 0.end
(optional): The index at which to end filling the array (not included). Default is the length of the array.
Example
Consider the following example:
let arr = [1, 2, 3, 4, 5];
arr.fill(0, 2, 4);
console.log(arr) // Output: [1, 2, 0, 0, 5]
In this example, the fill()
method is used to fill the elements of the arr
array from index 2 to 4 with the value 0.
Output
The output of the above example is:
[1, 2, 0, 0, 5]