How To Create Two Dimensional Array In JavaScript Dynamically

In this tutorial, we will learn how to create a two-dimensional array in JavaScript dynamically. Two-dimensional arrays are especially useful when dealing with matrices, tables, or any other data types that need to be stored in rows and columns.

JavaScript does not have built-in support for two-dimensional arrays, but you can mimic them using arrays of arrays. By the end of this tutorial, you will be able to create, populate and access elements of a two-dimensional array in JavaScript.

Step 1: Initialize a Two-Dimensional Array

The first step in creating a two-dimensional array is to initialize it. To do this, declare an array and then fill it with arrays. You can define the size of each nested array as well.

Here’s an example of initializing a 3×3 two-dimensional array:

In this example, we first create a new array called matrix. Then, we iterate through its elements and replace them with new arrays, effectively creating a two-dimensional array.

Step 2: Fill the Two-Dimensional Array with Data

Once the two-dimensional array is initialized, you can fill it with data. To do this, iterate through the rows and columns of the array, assigning a value to each cell:

In this example, we use a nested loop to iterate through the two-dimensional array, setting each cell to the product of its row and column indices.

Step 3: Access Elements of the Two-Dimensional Array

To access elements of the two-dimensional array, use the square bracket notation with the row and column index:

The Full Code

Output

The value of the element at row 1, column 2 is: 2

Conclusion

In this tutorial, we learned how to create, populate, and access elements in a two-dimensional array in JavaScript. Although JavaScript does not have native support for two-dimensional arrays, you can use arrays of arrays to achieve the same functionality. By following this technique, you can create matrices and other data types that rely on a grid-like structure.