In JavaScript, we can easily create an array of zeros. The easiest way to create an array of zeros only is to use the javascript array fill() method.
var array_of_zeros = Array(10);
array_of_zeros.fill(0);
console.log(array_of_zeros);
#Output:
[0,0,0,0,0,0,0,0,0,0]
A second way to make an array of zeros in JavaScript is to use a for loop.
var array_of_zeros = [];
for ( var i=0; i<arraySize; i++; ){
array_of_zeros[i] = 0;
}
In the code above, the variable arraySize is however long you want the array to be. So let’s say we wanted an array of size 10 containing all zeros.
var array_of_zeros = [];
for ( var i=0; i<10; i++ ){
array_of_zeros[i] = 0;
}
console.log(array_of_zeros);
#Output:
[0,0,0,0,0,0,0,0,0,0]
In JavaScript, creating an array of zeros can be useful if we want to initialize an array to count or fill later on in our program.
There are a number ways that we can create and fill an array with zeros.
The easiest way to create an array with only zeros is by using the fill() method.
Once again, here is our code to create an array of zeros:
var array_of_zeros = Array(10);
array_of_zeros.fill(0);
You can use this method to create an array that contains any value as shown below in JavaScript.
var array_of_a = Array(10);
array_of_a.fill('a');
console.log(array_of_a);
#Output:
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
Create a function that returns an Array of Zeros in JavaScript at a Specific Size
To make things easier for us, we will take our code from above and put it in a function. The function will take one value, an integer, that will be the size of the array we want and fill it with zeros.
function arrayOfZeros(arr_size){
var array_of_zeros = Array(arr_size);
array_of_zeros.fill(0);
return array_of_zeros;
};
And here is our function in action:
function arrayOfZeros(arr_size){
var array_of_zeros = Array(arr_size);
array_of_zeros.fill(0);
return array_of_zeros;
};
console.log(arrayOfZeros(5));
#Output:
[0,0,0,0,0]
Create a function that returns an Array of any Values at a Specific Size
We can also improve upon our previous function to make an array containing anything at a specific size.
function arrayOfAnything(arr_size,arr_value){
var array_of_anything = Array(arr_size);
array_of_anything.fill(arr_value);
return array_of_anything;
};
And here is our function in action:
function arrayOfAnything(arr_size,arr_value){
var array_of_anything = Array(arr_size);
array_of_anything.fill(arr_value);
return array_of_anything;
};
console.log(arrayOfAnything(7,"hello"));
#Output:
['hello', 'hello', 'hello', 'hello', 'hello', 'hello', 'hello']
Hopefully this article has been useful for you to learn how to use JavaScript to make an array of zeros.