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.

💡 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
const matrix = [
[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
console.log(matrix[0][1]); // Access row 0, column 1
// Output: 2
console.log(matrix[2][2]); // Access row 2, column 2
// Output: 9
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
const jagged = [
[1, 2],
[3, 4, 5],
[6]
];
console.log(jagged[1][2]); // 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
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}
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.
| Operation | Example |
|---|---|
| Create | const arr = [[1,2], [3,4]]; |
| Access | arr[1][0] // 3 |
| Edit | arr[0][1] = 9; |
| Iterate | Nested 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).
Quick Knowledge Check
Test what you just learned
Question 1 of 2
How do you access the element '5' in this array?const arr = [[1,2], [3,4,5], [6]];
Question 2 of 2
What will console.log(arr[0][3]) output if arr = [[1,2,3], [4,5,6]]?
Loading results...