We’ve to create a JavaScript array filled with all zeroes in our code.
In this article, we’ll look at how to create a zero-filed JavaScript array.
Array.prototype.fill
We can use the fill
array method to fill all the entries of an array with the values we want.
For instance, we can write:
const arr = new Array(10).fill(0);
console.log(arr);
The Array
constructor takes the length of an array if we only pass one argument into it.
fill
takes the value we want to fill the array with.
Then arr
is [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
.
fill
is available since ES6.
The apply and map Methods
We can also use the Array.apply
method to create an empty array that we can use the map
method with.
Then we pass in a callback that returns the value we want into the map
method.
For instance, we can write:
const arr = Array.apply(undefined, Array(10)).map(() => 0);
console.log(arr);
We call apply
with Array(10)
to create an array with 10 slots that we can fill with map
.
Then in map
, we just pass in a callback that returns 0 to fill all the entries with zeroes.
So we get the same result as the previous example.
Array.from
The Array.from
method is an array static method that lets us return an array derived from another array.
So we can use it to map the values from one array to another, including an empty array.
For instance, we can write:
const arr = Array.from(Array(10), () => 0)
console.log(arr);
We call Array.from
with Array(10)
to let us map the empty array with 10 slots to an array with stuff inside.
The 2nd argument is a callback that returns 0 so we fill all the entries with zeroes.
Therefore, we get the same result as before.
Another way to use Array.from
is to pass in an object with the length
property set to the array length we want.
To do this, we write:
const arr = Array.from({
length: 10
}, () => 0)
console.log(arr);
And we get the same result as before.
Conclusion
We can create a zero-filled array with JavaScript by using the fill
method or the Array.from
method.
Also, we can use the Array
constructor to create an array.