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

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:


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.


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.

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

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version

Leave a Reply

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