Use the Array fill() method if you want to fill specified values into an Array in JavaScript. It returns the modified array and returns undefined if no element satisfies the condition.
array.fill(value, start, end)
The start and end positions can be specified. If not, all elements will be filled.
The fill()
method takes up to three parameters:
value
(required): The value to fill the array with.start
(optional): The index to start filling the array (default is 0).end
(optional): The index to stop filling the array (default is the length of the array).
JavaScript Array fill
Simple example code with string and number arrays.
<!DOCTYPE html>
<html>
<body>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.fill("Kiwi");
console.log(fruits);
const array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
</script>
</body>
</html>
Output:
Note: The fill()
method overwrites the original array. If you want to create a new array without modifying the original one, you can combine the fill()
method with the spread syntax:
const array = [1, 2, 3, 4, 5];
const newArray = [...array].fill(0);
console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(newArray); // Output: [0, 0, 0, 0, 0]
In this case, the original array
remains unchanged, and the newArray
is a separate array with the desired values filled in.
Comment if you have any doubts or suggestions on this JS Array function.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version