Create A Zero Filled Array In JavaScript

To create a zero filled array in JavaScript, you can use the fill() method. This method takes two arguments, the first is the value to fill the array with and the second is the start index. The fill() method will fill the entire array with the specified value.

create a zero filled array in JavaScript

Create A Zero Filled Array In JavaScript

For example, if you wanted to create an array of 10 zeros, you would do the following:

var myArray = new Array(10).fill(0);

console.log(myArray); // Output: //[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

As you can see from the output, the fill() method filled the entire array with the value of zero.

In the above code, we have created a new array using the Array() constructor. This array has a length of 10. The only argument we passed to the Array() constructor is the length of 10.

Once we have created the array, we use the fill() method to fill it with zeros. The fill() method takes two arguments, the first is the value to fill the array with and the second is the start index. The fill() method will fill the entire array with the specified value, if the second argument is not provided.

If you wanted to start filling the array with zeros from the index of 2, you would do the following:

var myArray = new Array(10).fill(0, 2);

console.log(myArray); //[undefined, undefined, 0, 0, 0, 0, 0, 0, 0, 0]

As you can see from the output, the fill() method filled the array with zeros starting from index 2.

The fill() method is a great way to create a zero filled array in JavaScript. It is simple and easy to use. Plus, it is supported in all major browsers.

If you are looking for an alternative method to create a zero filled array, you can use the Array.from() method. The Array.from() method creates a new array from an array-like or iterable object.

For example, if you wanted to create an array of 10 zeros, you would do the following:

var myArray = Array.from({length: 10}, () => 0);

console.log(myArray); //[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

As you can see from the output, the Array.from() method created an array of 10 zeros.

The method takes two arguments, the first is the array-like or iterable object and the second is the map function. The map function is used to fill the new array with the desired values. In this case, we are using it to fill the array with zeros.

You can even use the traditional for loop to create a zero filled array. The following example shows how you would do this:

var myArray = [];

for(var i = 0; i < 10; i++){

  myArray.push(0);

}

console.log(myArray); //[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

As you can see from the output, the for loop created an array of 10 zeros.

Conclusion – Create A Zero Filled Array In JavaScript

Creating a zero filled array in JavaScript is easy. You can use the fill() method or the Array.from() method. You can even use a traditional for loop. Whichever method you choose, it is simple and easy to do.

Leave a Reply