What is the Most Efficient Way to Create a Zero Filled Array in JavaScript

The most efficient way to create a zero filled array in JavaScript is to use the “Array.fill() method.” The Array.fill() method is used to fill all the elements of an array with a static value, which is 0 in this case.

Syntax

arr(length).fill(value)

Example 1: Using the Array.fill() method

const length = 5;

const zeroFilledArray = new Array(length).fill(0);

console.log(zeroFilledArray);

Output

[ 0, 0, 0, 0, 0 ]

Example 2: Creating a zero-filled array of size 3×3 (2D array)

To create a 2D zero-filled array of size 3×3, you can use the map() method and arrow functions.

const size = 3;

const zeroFilled2DArray = new Array(size)
 .fill(0)
 .map(() => new Array(size)
 .fill(0));

console.log(zeroFilled2DArray);

Output

[ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]

This method is concise and performs well for most use cases. However, if you’re working with extremely large arrays concerned about performance, you might want to benchmark different methods to find the most suitable one for your situation.

That’s it!

Leave a Comment