JavaScript Array fill() method
The fill()
method in JavaScript is used to fill all the elements of an array with a static value from a specified start index to an end index. This method modifies the original array and can be useful for initializing or resetting array values.
Syntax:
value
: The value to fill the array elements with. This can be any type of value, including objects or arrays.start
(optional): The index at which to start filling the array. The default is0
(the beginning of the array).end
(optional): The index before which to stop filling the array (not inclusive). The default is the length of the array.
Return Value:
- The modified array, with elements filled with the specified value.
Key Points:
- The
fill()
method modifies the original array and returns it. - If
start
is greater than or equal to the array length, the method does nothing. - If
end
is less than or equal tostart
, the method fills nothing. - Negative values for
start
orend
are treated as offsets from the end of the array.
Example 1: Basic usage
Example 2: Specifying start and end indices
Example 3: Using negative indices
Example 4: Filling an empty array
Example 5: Filling with an object
Summary:
- The
fill()
method is a powerful way to fill an array with a specified value, making it easy to initialize or reset array contents. - It is useful for preparing arrays for further manipulation or when you need to set default values.
- Since it modifies the original array, care should be taken to avoid unintentional changes to existing data.