Example 1: Using the Array.fill() method
const length = 5; const zeroFilledArray = new Array(length).fill(0); console.log(zeroFilledArray);
[ 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);
[ [ 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.