Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptWhat is the most efficient way to create a zero filled array...

What is the most efficient way to create a zero filled array in JavaScript ?

The purpose of this article is to determine the most efficient way to create a zero-filled JavaScript Array. The most efficient way to create a zero-filled JavaScript array is to use the Array fill method. The fill() method allows you to fill all the elements of an array with a static value, which in this case would be zero.

Syntax:

arr(length).fill(value)

Approach:

  • The Array() constructor creates an array with the specified length, and the fill() method fills all the elements of the array with a static value, which in this case is zero.
  • The code creates an array of length 10 filled with zero using the Array() constructor with the fill() method, and stores the resulting array in the filledArray variable.
  • Finally, the console.log() method is used to print the array to the console.

This approach is an efficient way to create a zero-filled array because it requires only one line of code and doesn’t require any loops or conditional statements. The fill() method is highly optimized for performance and can fill large arrays quickly.

Example1: Creating a zero-filled array of length 10

Javascript




<script>
      // Creating an array filled with zero's in efficient way
      var filledArray = Array(10).fill(0);
    
      // Printing output array
      console.log(`Array filled with zero's  values is [${filledArray}]`);
</script>


Output:

Array filled with zero's  values is [0,0,0,0,0,0,0,0,0,0]

Example 2: Creating a zero-filled array of size 3×3 (2D array), here we will also use map and arrow function as well.

Javascript




<script>
    // Creating 2d array filled with zero values 
    const arr2D = new Array(3).fill().map(() => new Array(3).fill(0));
    // Printing output
    console.log(`2D array filled with zero's is`); 
    console.log(arr2D)
</script>


Output:

2D array filled with zero's is
VM1475:6 (3) [Array(3), Array(3), Array(3)]

Note: To know more about Creating a zero-filled Array in JavaScript.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments