Skip to content
Related Articles

Related Articles

Creating a Zero-Filled Array in JavaScript

Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 29 Jun, 2022
Improve Article
Save Article

To create a zero-filled array in JavaScript, we can use the Array fill() method or the Array.from() method. Array constructor can also be used to create a zero-filled array.

Method 1: Array.prototype.fill: The fill() method is used to change the elements of the array to a static value from the initial index (by default 0) to the end index (by default array.length). The modified array is returned.

Syntax:

fill(value)
// or
fill(value, start)
// or
fill(value, start, end)
  • value: It is the value to fill the array with.
  • start: It is the starting index of an array (default 0).
  • end: It is the end index of an array.

Example 1: The following code snippet demonstrates the fill() method with 0 value.

HTML




<html>
<body>
    <h2 style="color:green">Welcome To GFG</h2>
  
    <script>
        const arr = new Array(5).fill(0);
        console.log(arr);
    </script>
</body>
</html>


Output:

 

Array constructor takes the size of an array as a parameter if we pass one argument into it. fill() method takes the value we want to fill in the array.

Note: fill() method is available since ES6.

Method 2: In the below example, we use apply() method to create an array of 5 elements that can be filled with the map() method. In the map() method, we pass in a callback that returns 0 to fill all the indexes with zeros.

Apply() and Map(): Array.apply() method is used to create an empty array in which we can use the map() method to store each element as key-value pair.

Javascript




const arr = Array.apply(null, Array(5)).map(() => 0);
console.log(arr);


Output:

 

Method 3: Array.from()  This method is used to create a new,shallow-copied array from an array-like or iterable object.

Syntax:

Array.from(arrayLike, (element) => { /* ... */ } )

Example: In the below example, Array.from() is called which let us map an empty array of size 5 to an array with some elements inside.The second argument is a callback that returns 0 which is used to fill the array.

Javascript




const arr = Array.from(Array(5), () => 0)
console.log(arr);


Output:

 

The same result can be obtained by passing an object with the length property using the Array.from() method.

Javascript




const arr = Array.from({  
  length: 5  
}, () => 0)  
console.log(arr);


Output:

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!