Categories
JavaScript Answers

How to declare an empty two-dimensional array in JavaScript?

Spread the love

Sometimes, we want to declare an empty two-dimensional array in JavaScript.

In this article, we’ll look at how to declare an empty two-dimensional array in JavaScript.

How to declare an empty two-dimensional array in JavaScript?

To declare an empty two-dimensional array in JavaScript, we can use the array fill method.

For instance, we write

const matrix = new Array(5).fill(0).map(() => new Array(4).fill(0));

to call Array with 5 to create an array with 5 empty slots.

Then we call fill to fill the slots with undefined.

Next we call map with a callback to return an array with 4 empty slots and fill them with 0 with fill.

Conclusion

To declare an empty two-dimensional array in JavaScript, we can use the array fill method.

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 *