The fill() method in JavaScript is used to fill all the elements of an array from a start index to an end index with a static value. It modifies the original array and returns the modified array.
Syntax
array.fill(value, start, end);
Parameters
Parameters | Descriptions |
---|---|
value | The value to fill the array with. |
start (Optional) | The index to start filling the array. Defaults to 0. |
end (Optional) | The index to end filling the array (not inclusive). Defaults to array.length. |
Return Value
Return Type | Description |
---|---|
Array | The modified array with the filled elements. |
Example 1: Filling Array with a Static Value
This code demonstrates how to use the fill() method to fill an array with a static value.
let arr = [1, 2, 3, 4, 5]; arr.fill(0); console.log(arr);
Output:
[ 0, 0, 0, 0, 0 ]
Example 2: Filling Array with a Static Value from Start Index
This code demonstrates how to use the fill() method to fill an array with a static value from a specific start index.
let arr = [1, 2, 3, 4, 5]; arr.fill(0, 2); console.log(arr);
Output:
[ 1, 2, 0, 0, 0 ]
Example 3: Filling Array with a Static Value within a Range
This code demonstrates how to use the fill() method to fill an array with a static value within a specific range.
let arr = [1, 2, 3, 4, 5]; arr.fill(0, 1, 4); console.log(arr);
Output:
[ 1, 0, 0, 0, 5 ]
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
45 | 12 | 31 | 32 | 8 |