Skip to content

JavaScript fill array with 0 | Array fill() Method examples

  • by

JavaScript fill array with 0 use fill() method. This method will fill the specified or all elements in an array with a static value. This method overwrites (Change) the original array.

JavaScript fill array with 0 Examples

Let’s see the HTML example code with different ways:

Fill (change) the existing elements of Array

It will fill with zero weather an array have string or integer (number) elements:-

Same way you can Fill all the array elements with a another static value:

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        var fruits = ["Banana", "Orange", "Apple", "Mango"];
        fruits.fill(0); 
        console.log(fruits);
    </script>
</body>
</html>

Output:

JavaScript fill array with 0 HTML example

Initialise JavaScript array with zeros

A new Array(3).fill(0) will give you [0, 0, 0]. You can fill the array with any value like new Array(5).fill(‘abc’).

Let’s create array with length of 5 and filled with zeros.

<!DOCTYPE html>
<html> 
<body>

    <script type="text/javascript">
        var arr = new Array(5).fill(0)
        console.log(arr);
    </script>
</body>
</html>

Output:

Initialise JavaScript array with zeros example

Q: What is the most efficient way to create a zero-filled JavaScript array?

Answer: ES6 introduces Array.prototype.fill. It can be used like this. Not sure if it’s fast, but I like it because it’s short and self-describing.

new Array(len).fill(0);

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *