Categories
JavaScript Answers

How to create a 2D array of zeroes in JavaScript?

Spread the love

Sometimes, we want to create a 2D array of zeroes in JavaScript.

In this article, we’ll look at how to create a 2D array of zeroes in JavaScript.

How to create a 2D array of zeroes in JavaScript?

To create a 2D array of zeroes in JavaScript, we can use some array methods.

For instance, we write:

const zeroes = Array(3).fill().map(() => Array(3).fill(0));
console.log(zeroes)

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

Then we call fill and map to fill the empty slots and map them to arrays with 0’s in it.

Therefore, zeroes is:

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

Conclusion

To create a 2D array of zeroes in JavaScript, we can use some array methods.

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 *