Skip to content

JavaScript initialize array with 0 | Example code

  • by

The most basic way to JavaScript initialize an array with 0 is to hardcode each value. The below code will initialize an array of length 7 filled with zeros.

var array = [0,0,0,0,0,0,0]

To initialize an array with zeros in JavaScript, you can use the Array() constructor along with the fill() method. Here’s an example:

const length = 5; // specify the length of the array
const array = Array(length).fill(0);

console.log(array);

Note: This method is efficient but it’s not practical if the array is very large

JavaScript initializes an array with a 0

Simple example code using Loops. First initializes an array of length 7 then uses for-loop to set each element of the array to 0. Or you can also push 7 zeros into an empty array.

<!DOCTYPE html>
<html>
<body>

  <script>
    var arr1 = new Array(7);
    for(var i=0; i<arr1.length; ++i)
      arr1[i] = 0
    console.log(arr1)

    var arr2 = []
    for(var i=0; i<7; ++i)
      arr2.push(0)
    console.log(arr2)
  </script>

</body>
</html> 

Output:

JavaScript initialize array with 0

Using fill()

var array = new Array(7).fill(0);
for(var i=0;i<array.length;++i)
  console.log(array[i])
  1. Array.fill() fills an array with a specified static value.
  2. Array.fill(0) will fill the array with 0.

This method overwrites the actual array.

Alternatively, you can use the Array.from() method to achieve the same result:

const length = 5;
const array = Array.from({ length }, () => 0);

console.log(array);

Using split() and join()

var array = new Array(8).join('0').split('');
for(var i=0;i<array.length;++i)
  console.log(array[i])

Comment if you have any doubts or suggestions on this Js Array 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading