JavaScript Answers

How to Declare an Empty Two-Dimensional Array in JavaScript?

Spread the love

To declare an empty two-dimensional array in JavaScript, we can create an empty array with the Array constructor.

Then we call map on that array with a callback that returns an array with the Array constructor to create the nested arrays.

For instance, we can write:

const nested = [...Array(3)].map(x => Array(5).fill(0))

We call Array with 3 to create an array with length 3.

Then we spread that into a new array to create a copy of it.

Next, we call map on the copied array with a callback that returns an array with length with all values in it set to 0 with Array(5).fill(0) .

As a result, nested is a two-dimensional array with length 3, with each nested array with length 5 and all values inside it set to 0.

If we want the nested arrays to be empty, we can omit the fill call.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.