The fill()
method in JavaScript is used to fill all the elements of an array with a static value. This method modifies the array in place, meaning that it changes the existing array instead of creating a new one.
Here is an example of how the fill()
method works:
const array1 = [1, 2, 3, 4, 5];
// fill the array with the value 0
const result = array1.fill(0);
// the result will be: [0, 0, 0, 0, 0]
In the code example above, we first declare an array called array1
that contains the numbers 1
through 5
. We then use the fill()
method to fill the array with the value 0
. The fill()
method takes a single argument, which is the value that should be used to fill the array. In this case, we use 0
as the fill value.
As a result of calling the fill()
method, the array1
array is modified in place and now contains the following elements: 0
, 0
, 0
, 0
, 0
.
In addition to filling the entire array with a static value, the fill()
method also allows you to specify a start index and an end index to specify a range of elements that should be filled. For example:
const array1 = [1, 2, 3, 4, 5];
// fill the middle three elements with the value 0
const result = array1.fill(0, 1, 4);
// the result will be: [1, 0, 0, 0, 5]
In the code example above, we use the fill()
method to fill the middle three elements of the array1
array with the value 0
. We specify 1
as the start index and 4
as the end index, which means that the fill()
method will only affect the elements at indices 1
through 3
(inclusive) of the array.
As a result of calling the fill()
method, the array1
array is modified in place and now contains the following elements: 1
, 0
, 0
, 0
, 5
.
Leave a Reply