April 2, 2025

Many times I am using some example array for articles and always the first step is to initialize the array. So today we are going to see a simple way to do it and see how we can fill an array with numbers in Javascript. The idea is to fill it in with the same number as many times as we want.

That is, if I want to have an array where the number 2 appears 10 times, I don’t have to write something like this:
let myiarray = [2,2,2,2,2,2,2,2,2,2];

The first thing is to create an array of the positions that we want, for this we invoke the constructor of the Array class
indicating as a parameter the number of elements that the array will have:
let myiarray = new Array (10);

In this case we will have an array prepared to hold 10 elements but it will be empty. That is why if we go through it we will see that there is no element.

The next step will be to fill the array with numbers. In this case we are going to fill it with the number 2 in its 10 positions. For this we have to know the .fill () method
of the Array object
. The syntax of the .fill () method
is the next:
arr.fill (value [, start = 0 [, end = this.length]])

In its syntax we see that the first parameter is the value with which we want to fill the array. The second parameter will be the initial position from where we want to fill it, that is, it is not necessary that we fill the array completely but we can do it partially. And the last parameter will be the final position where we will finish filling the array. This parameter is optional and if it does not appear, it takes the size of the array as the value, that is, it will fill up to the last position.

So, in order to fill our initial array with the 10 positions with the value 2 we will write the following:
myiarray.fill (2,0,10);

Although we could have skipped the last parameter and wrote the following:
miarray.fill (2.0);

Now, if we go through the array to show its values, for example through a for each loop.
myiarray.forEach (function (item, index, arr) {
    console.log (“Position” + index + “:” + item);
});

We will see that the result per console is the following:
Position 0: 2
Position 1: 2
Position 2: 2
Position 3: 2
Position 4: 2
Position 5: 2
Position 6: 2
Position 7: 2
Position 8: 2
Position 9: 2

In this simple way and using the .fill () method
We will have managed to fill an array with numbers in Javascript.

Leave a Reply

Your email address will not be published. Required fields are marked *