The fill() method of the Array class in JavaScript fills all the elements of an array from a start index to an end index with a static value. This method modifies the original array.
There are 3 variations for the syntax of Array.fill() method. They are:
fill(value)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
value | required | The value to fill the array with. |
This method fills all the elements of an array with a static value.
Returns value of type Array
.
fill(value, start)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
value | required | The value to fill the array with. |
start | optional | The start index, defaults to 0. |
This method fills all the elements of an array from the start index with a static value.
Returns value of type Array
.
fill(value, start, end)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
value | required | The value to fill the array with. |
start | optional | The start index, defaults to 0. |
end | optional | The end index, defaults to the array's length. |
This method fills all the elements of an array from the start index to the end index with a static value.
Returns value of type Array
.
In JavaScript, we can use the fill() method to fill all the elements of an array with a static value.
For example,
const arr = [1, 2, 3, 4, 5];
arr.fill(0);
console.log(arr);
[0, 0, 0, 0, 0]
We can use the fill() method to fill elements of an array from a specified start index with a static value.
For example,
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.fill('x', 2);
console.log(arr);
['a', 'b', 'x', 'x', 'x']
We can use the fill() method to fill elements of an array from a specified start index to an end index with a static value.
For example,
const numArr = [1, 2, 3, 4, 5];
numArr.fill(9, 1, 3);
console.log(numArr);
[1, 9, 9, 4, 5]
In this JavaScript tutorial, we learned about fill() method of Array: the syntax and few working examples with output and detailed explanation for each example.