What is a two-dimensional array?
A two-dimensional array (or array of arrays) is a data structure in which each element is itself an array.
Put simply, it is a table: rows and columns, like in Excel or a matrix.
Example of a two-dimensional array:
javascript
const matrix = [
[1, 2, 3], // ← row 0
[4, 5, 6], // ← row 1
[7, 8, 9] // ← row 2
];Here:
matrix[0]→[1, 2, 3](the first row)matrix[1][2]→6(an element from the second row, third column)
Visually:
javascript
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | 1 | 2 | 3 |
| 1 | 4 | 5 | 6 |
| 2 | 7 | 8 | 9 |
How to access elements
javascript
console.log(matrix[0][0]); // 1
console.log(matrix[2][1]); // 8The first index is the row, the second is the column.
How to iterate over all elements
With nested loops:
javascript
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}iis the row number,jis the column number.
Example use case:
Two-dimensional arrays are often used for:
- storing tables and matrices of numbers;
- representing game boards (for example, chess, tic-tac-toe);
- storing coordinates (x, y);
- working with images, pixels, grids, and so on.
Creating an empty two-dimensional matrix:
javascript
const rows = 3;
const cols = 4;
const matrix = Array.from({ length: rows }, () => Array(cols).fill(0));
console.log(matrix);
/*
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
*/In short:
| Term | Meaning |
|---|---|
| Two-dimensional array | An array where each element is an array |
| Indexing | [row][column] |
| Example | matrix[1][2] → 6 |
| Often used for | Tables, grids, coordinates, matrices |
Summary: A two-dimensional array is a "table in code": an array made up of other arrays. It lets you conveniently store data as rows and columns.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.