Array.fill()
The Array.fill()
method in JavaScript is used to fill all or part of an array with a static value. You can specify the start and end indices for the portion of the array to fill. This method modifies the original array and returns it.
Syntax
fill(value)
fill(value, start)
fill(value, start, end)
Parameters
Parameter | Description |
---|---|
value | The value to fill the array with. |
start (optional) | The index at which to start filling. Default is 0 . |
end (optional) | The index at which to stop filling (not inclusive). Default is the array’s length. |
Return Value
The fill()
method returns the modified array after filling it with the specified value.
Examples
1. Filling the Entire Array
In this example, the entire array is filled with the specified value.
const array = [1, 2, 3, 4, 5];
array.fill(0);
console.log(array);
Output
[0, 0, 0, 0, 0]
array.fill(0)
replaces all elements in the array with0
.
2. Filling Part of the Array
This example demonstrates how to fill only a portion of the array, starting from a specific index.
const array = [1, 2, 3, 4, 5];
array.fill(9, 2);
console.log(array);
Output
[1, 2, 9, 9, 9]
array.fill(9, 2)
starts filling the array with9
from index2
to the end.
3. Filling with a Start and End Index
You can specify both the start and end indices for the portion of the array to fill.
const array = [1, 2, 3, 4, 5];
array.fill(7, 1, 4);
console.log(array);
Output
[1, 7, 7, 7, 5]
array.fill(7, 1, 4)
fills the array with7
from index1
to4
(exclusive).
4. Filling an Empty Array
The fill()
method can initialize an empty array with specific values.
const array = new Array(5);
array.fill('A');
console.log(array);
Output
['A', 'A', 'A', 'A', 'A']
An empty array of size 5 is filled with the value 'A'
.
5. Filling with Non-Primitive Values
When using objects, all references in the array point to the same object.
const array = new Array(3);
const obj = { key: 'value' };
array.fill(obj);
console.log(array);
obj.key = 'new value';
console.log(array);
Output
[ { key: 'value' }, { key: 'value' }, { key: 'value' } ]
[ { key: 'new value' }, { key: 'new value' }, { key: 'new value' } ]
- All elements share the same reference to
obj
, so modifyingobj
affects all elements in the array.