Categories
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 use the map method.

For instance, we write

const arr = [...Array(3)].map(() => Array(5));

to create an array with 3 empty slots with Array(3).

And then we spread them to a new array.

Then we call map with a callback that returns an array with 5 empty slots created with Array(5).

We now have a 3×5 empty 2d array.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *