JavaScript Array fill | Method

  • by

Use 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.

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:

JavaScript Array fill Method

Note: The fill() method overwrites the original array.

Do 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

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.