Multidimensional Arrays

In JavaScript, a multidimensional array is an array that contains other arrays as its elements. This structure allows you to represent data in a grid-like or matrix form, commonly used for tables, game boards, or coordinates.

Illustration of multidimensional_arrays
Illustration of multidimensional_arrays

💡 What is a Multidimensional Array?

It's essentially an array of arrays. Each element inside the main array is itself an array, which can contain values or even other arrays.

Here's how you can declare a simple 2D array (an array of arrays):

📌 Deep Dive: Creating a 2D Array

JAVASCRIPT
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];
Structure
[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

You can access elements by chaining indices. The first index selects the sub-array (row), and the second index selects the element within that sub-array (column).

📌 Deep Dive: Accessing Elements

JAVASCRIPT
console.log(matrix[0][1]); // Access row 0, column 1
// Output: 2

console.log(matrix[2][2]); // Access row 2, column 2
// Output: 9
Output
2
9

💡 Arrays Can Be Jagged

Sub-arrays can have different lengths, so multidimensional arrays don’t have to be perfect grids. For example:

📌 Deep Dive: Jagged Array Example

JAVASCRIPT
const jagged = [
  [1, 2],
  [3, 4, 5],
  [6]
];

console.log(jagged[1][2]); // 5
Output
5

To iterate through a multidimensional array, use nested loops: the outer loop for rows, and the inner loop for columns.

📌 Deep Dive: Iterating Over a 2D Array

JAVASCRIPT
for (let i = 0; i < matrix.length; i++) {
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(matrix[i][j]);
  }
}
Output
1
2
3
4
5
6
7
8
9

⚠️ Accessing Undefined Elements

If you try to access an index that doesn't exist in a sub-array, JavaScript returns undefined without throwing an error.

Common Multidimensional Array Operations
OperationExample
Createconst arr = [[1,2], [3,4]];
Accessarr[1][0] // 3
Editarr[0][1] = 9;
IterateNested loops or forEach

💡 Summary

  • Multidimensional arrays are arrays containing other arrays.
  • Access elements by chaining indices: array[row][column].
  • Nested loops are common for traversing these arrays.
  • Sub-arrays can be uneven in length (jagged arrays).