JavaScript Array fill() method is used to fill specified elements in an array with a value.
Syntax
array.fill(value, start, end)
Parameters
Parameter | Description |
---|---|
value(required) | It is the value to fill the array with |
start(optional) | The index to start filling the array (default index is 0) |
end(optional) | The index to stop filling the array (default is array. length) |
If you do not provide the start and end index, it will replace the whole array with the provided value.
Return value
It returns the modified array.
Visual Representation
Example 1: How to Use Array fill() method
let alphabets = ['A', 'B', 'C', 'D', 'E'];
alphabets.fill('X');
console.log(alphabets);
Output
[ 'X', 'X', 'X', 'X', 'X' ]
Example 2: Passing start and end parameter
let num = [7,14,21,28,35];
num.fill(8,2,4);
console.log(num);
Output
[ 7, 14, 8, 8, 35 ]
Example 3: Passing negative Index
let num = [7,14,21,28,35];
num.fill(9,-3);
console.log(num);
Output
[ 7, 14, 9, 9, 9 ]
Example 4: Start index is greater than a length
let num = [7,14,21,28,35];
num.fill(9,5,7);
console.log(num);
Output
[ 7, 14, 21, 28, 35 ]
In the above example, starting index 5 is beyond the last index of the array. So, no elements will be modified.
Example 5: Passing NaN as an argument
If the start and end number is not a number or NaN, it will not modify the array.
let num = [7,14,21,28,35];
num.fill(9,NaN,NaN);
console.log(num);
Output
[ 7, 14, 21, 28, 35 ]
Example 5: populating an empty array
const data = Array(5).fill("Ronaldo", 0);
console.log(data)
Output
[ 'Ronaldo', 'Ronaldo', 'Ronaldo', 'Ronaldo', 'Ronaldo' ]
Example 6: Using non-array objects
const data = { length: 6 }
console.log(Array.prototype.fill.call(data, 1))
Output
{ '0': 1, '1': 1, '2': 1, '3': 1, '4': 1, '5': 1, length: 6 }
Browser compatibility
- Google Chrome 45
- Microsoft Edge 12
- Firefox 31
- Safari 8
- Opera 32
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.