How to initialize an Array with Zeros or Objects in JavaScript

When you are working with arrays, sometimes you'll need to overwrite every element of the array with a specific value.
In JavaScript, this is called filling the array.
In this post, we'll learn how we can fill in an array with any value you want, including zeros and objects.
Filling an Array with Zeros
Let's start with an easy example, such as creating a new array, and then filling it with zeros.
To do this, we'll make use of the built-in fill()
method.
const array = new Array(3);
array.fill(0);
console.log(array);
(3) [0, 0, 0]
The fill()
method takes three parameters, the first is the value to fill the array with, the second is the start index, and the third is the end index.
The start and end index are optional, and if they are not specified, the fill will start at the beginning of the array and go to the end.
Let's look at filling in only the last two elements of the array.
const array = new Array(3);
array.fill(1, 1, array.length);
console.log(array);
(3) [empty, 1, 1]
Filling an Array with Objects
The fill()
method can also be used to fill an array with objects.
const array = new Array(3);
const value = {
name: "sabe.io:"
};
array.fill(value);
console.log(array);
(3) [{…}, {…}, {…}]
0: {name: 'sabe.io:'}
1: {name: 'sabe.io:'}
2: {name: 'sabe.io:'}
length: 3
Keep in mind that since you are filling this array with the same object, they will all have the same reference.
This means that modifying one of the objects will modify all of them.
Let's see this in action:
const array = new Array(3);
const value = {
name: "sabe.io:"
};
array.fill(value);
array[0].name = "sabe.io/hello";
console.log(array);
(3) [{…}, {…}, {…}]
0: {name: 'sabe.io/hello'}
1: {name: 'sabe.io/hello'}
2: {name: 'sabe.io/hello'}
length: 3
To avoid this scenario, you can use the Array.from()
method, which will create and automatically populate your array with your specified value:
const value = () => ({
name: "sabe.io"
});
const array = Array.from({ length: 3 }, value);
array[0].name = "sabe.io/hello";
console.log(array);
(3) [{…}, {…}, {…}]
0: {name: 'sabe.io/hello'}
1: {name: 'sabe.io'}
2: {name: 'sabe.io'}
length: 3
As you can see, the first element of the array is now modified, but the other two are not, which is what you want.
Conclusion
In this post, we looked at how to fill an array with zeros, and how to properly fill an array with objects.
Simply use the fill()
method to fill in your array with any value you want, which also includes strings.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!