This post will discuss how to create a 2D array pre-filled with a specified value in JavaScript.

To create a 2D array of fixed dimensions initialized with a specified value, you can use any of the following methods:

1. Using Array constructor

In JavaScript, 2D arrays can be easily created using the array constructor and the for-loop. To initialize it with the specific value, use fill() method.

Download  Run Code

2. Using Array.from() function

The Array.from() method creates a new array instance from the specified array and optionally map each array element to a new value. This can be used as follows for creating a 2D array:

Download  Run Code

 
You can simplify this to the following code:

Download  Run Code

3. Using Array.prototype.map() function

Alternatively, you can directly call the map() function on the array, as shown below:

Download  Run Code

4. Using array literal notation

Finally, 2D arrays can also be created using the array literal notation. The following code example shows how to implement this using two loops:

Download  Run Code

That’s all about creating a 2D array filled with the specified value in JavaScript.