How to use Array.push() method In Javascript

In this example, the Array.push() method is used to add elements to the end of the array. The for loop is used to repeat the push method 10 times to add the value 0 to the array.

Javascript
let myArray = [];
for (let i = 0; i < 10; i++) {
    myArray.push(0);
}
console.log(myArray);
Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How to fill an array with given value in JavaScript ?

In JavaScript, an array is a collection of elements that can be of any data type. Sometimes, it is necessary to fill an array with a specific value for a given number of times. For example, an array of length 10 needs to be filled with the value 0, or an array of length 5 needs to be filled with the value “Hello”.

Approach: There are several ways to fill an array with a given value in JavaScript. 

Similar Reads

Using Array.fill() method:

One of the most common ways is to use the Array.fill() method. This method modifies the original array and fills it with a given value for a specified number of times....

Using for loop:

In this example, a for loop is used to iterate over the array and fill it with the value “Hello”. The for loop starts at index 0 and goes until the end of the array, which is specified by the myArray.length property....

Using Array.push() method:

In this example, the Array.push() method is used to add elements to the end of the array. The for loop is used to repeat the push method 10 times to add the value 0 to the array....

Using the spread operator:

In this example, the spread operator is used to expand the Array(5) which creates an array with 5 empty slots, and then the Array.map() method is used to fill all the empty slots with the value “Hello”...

Using the Array.from():

Use the following syntax to fill the array of size n with 0 value. Use any value in place of 0....

Using repeat and split on a String

Use the repeat method to create a string with repeated characters and then split it into an array. Convert each element as needed. This approach is simple for filling arrays with identical values....

Contact Us